加载特定的XML节点值C#

时间:2012-08-08 15:33:30

标签: c# xml

我试图获取标签名称为"所有节点的属性值;事件"到WindowsForm上的一个comboBox。我在下面尝试过这段代码,但是,comboBox中没有任何内容。

 if (selectEventComboBox.SelectedIndex != -1)
    {
        string filePath = 
              Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) 
              + "\\" + selectFileComboBox.SelectedItem.ToString() 
              + "dogs.xml";
        XmlDocument doc = new XmlDocument();
        doc.Load(filePath);

        XmlNodeList eventList = doc.GetElementsByTagName("Event");
        for (int count = 0; count < eventList.Count; count++)
        {
            selectEventComboBox.Items.Add(eventList[count].Attributes.ToString());
        }
    }

1 个答案:

答案 0 :(得分:2)

这很好用

XmlDocument doc = new XmlDocument();
doc.Load("myxml.xml");
XmlNode root = doc.DocumentElement;
XmlNodeList nodeList = root.SelectNodes("//Event");

for (int i = 0; i < nodeList.Count; i++)
{
    Console.WriteLine("row: {0}, InnerText: {1}, ID: {2}",i, nodeList[i].InnerText, nodeList[i].Attributes["id"].Value);
}

myxml.xml的内容

<?xml version="1.0" encoding="utf-8" ?>
<root>
    <Event id="1">Event one</Event>
    <Event id="2">Event two</Event>
    <Event id="3">Event three</Event>
    <Event id="4">Event four</Event>
</root>

enter image description here