C#Xml节点读取 [英] C# Xml node reading

查看:73
本文介绍了C#Xml节点读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读取一个xml文件,并试图将其中一个节点填充到一个下拉框中.我已经做到了.但是,下拉框显示了每个节点的内部文本,我需要消除重复项.

I am reading a xml file and trying to populate one of the nodes into a dropdownbox. I''ve managed to do this. However the dropdownbox shows every node innertext and I need to get rid of the duplicates.

XmlDocument doc = new XmlDocument();

            doc.Load(xml_Url);

            XmlNodeList nodes = doc.SelectNodes("JOBS/JOB/CATEGORIES/CATEGORY");
            

            foreach (XmlNode node in nodes)
            {

             DropDownList1.Items.Add(newListItem(node.FirstChild.InnerText, node.LastChild.InnerText));

            }

推荐答案

以下使用的是Xml.Linq(相对于.Net 2.0中的原始Xml类,我更喜欢它).警告-我是从记忆中做到这一点的,因此您可能需要对其进行一些微调.)

The following usis Xml.Linq (I prefer this to the original Xml classes in .Net 2.0). Caveat - I did this from memory, so you may have to tweak it a little).

XDocument doc = XDocument.Load(xm_Uri);
XElement root = doc.Element("JOBS/JOB/CATEGORIES");
foreach (XElement element in root.Elements())
{
    DropDownList1.Items.Add(element.Element("Category").Value.ToString());
}


您可以使用ListBox(我假设您的DropDownBox就是)方法:DropDownList1.Items.Contains(entry)如下:
You can use the ListBox (which is what your DropDownBox is I assume) method: DropDownList1.Items.Contains(entry) as follows:
  foreach (XmlNode node in nodes)
            {
      if(!DropDownList1.Items.Contains(node.FirstChild.InnerText)
            { DropDownList1.Items.Add(newListItem(node.FirstChild.InnerText, node.LastChild.InnerText));
}
            }



这将检查列表中是否已存在新条目,如果没有,则仅添加它.

希望这会有所帮助.



This will check to see if the new entry is already in the list and only add it if not.

Hope this helps.


这篇关于C#Xml节点读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆