2

我正在尝试将标签名称为“事件”的所有节点的属性值获取到 WindowsForm 上的组合框中。我在下面尝试了这段代码,但是,组合框中没有填充任何内容。

 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());
        }
    }
4

1 回答 1

3

这工作正常

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>

在此处输入图像描述

于 2012-08-08T15:50:07.090 回答