C# XML 读取子节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14920082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:27:11  来源:igfitidea点击:

XML reading child nodes

c#xml

提问by Ben

I have an XML document and I am trying to get the childnodes of an element called Unit

我有一个 XML 文档,我正在尝试获取名为的元素的子节点 Unit

My XML Doc is layed out like so:

我的 XML 文档布局如下:

<Unit>
    <id>3</id>
    <name>System Information</name>
    <description>null</description>
    ... other ...
</Unit>

This is the code I am using to try and read them.

这是我用来尝试阅读它们的代码。

public void Load()
{
    FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
    XmlDocument xmldoc = new XmlDocument();
    XmlNodeList xmlnode;

    xmldoc.Load(fs);
    xmlnode = xmldoc.GetElementsByTagName("Units");

    for (int i = 0; i < xmlnode.Count; i++)
    {
        string str = string.Format("ID: {0}\r\nName:{0}", xmlnode[i].ChildNodes.Item(0).InnerText, xmlnode[i].ChildNodes.Item(1).InnerText);
        MessageBox.Show(str);
    }
}

But the problem is, when I try and get them, instead of getting item 0 or item 1, it displays all the items and not the items i have selected.

但问题是,当我尝试获取它们时,它不是获取项目 0 或项目 1,而是显示所有项目,而不是我选择的项目。

采纳答案by Maris

As I can see from your xml and code. You have error in line:

正如我从您的 xml 和代码中看到的那样。你有错误:

 xmlnode = xmldoc.GetElementsByTagName("Units");

change it on:

改变它:

 xmlnode = xmldoc.GetElementsByTagName("Unit");

回答by MarcinJuraszek

You have a typo in element name: should be Unitinstead of Units.

您在元素名称中有一个拼写错误:应该是Unit而不是Units

However, have you tried using LINQ to XML instead of XmlDocument?

但是,您是否尝试过使用 LINQ to XML 而不是XmlDocument

public void Load()
{
    var doc = XDocument.Load(filePath);

    foreach(var unit in doc.Descendants("Unit"))
    {
        string str = string.Format("ID: {0}\r\nName:{0}", unit.Element("id").Value, unit.Element("name").Value);
        MessageBox.Show(str);
    }
}

回答by Sergey Berezovskiy

With Linq to Xml you can easily parse your xml into (anonymous) strongly typed objects:

使用 Linq to Xml,您可以轻松地将 xml 解析为(匿名)强类型对象:

public void Load()
{
    FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);

    var xdoc = XDocument.Load(fs);
    var units = from u in xdoc.Descendants("Unit")
                select new {
                   Id = (int)u.Element("id"),
                   Name = (string)u.Element("name")
                };

    foreach(var unit in units)
    {
       // thanks God for IntelliSense!
       MessageBox.Show(String.Format("ID:{0}\r\nName:{1}", unit.Id, unit.Name));
    }
}

Well, actually if you only need to show those values in message box, you can even write all code in one line. But I prefer first approach, when retrieving data and displaying them are separated (ideally in separate methods):

好吧,实际上如果您只需要在消息框中显示这些值,您甚至可以将所有代码写在一行中。但我更喜欢第一种方法,在检索数据和显示它们时是分开的(最好在单独的方法中):

XDocument.Load(filePath)
         .Descendants("Unit")
         .Select(u => String.Format("Id:{0}\nName:{1}", (int)u.Element("id"), (string)u.Element("name"))
         .ToList()
         .ForEach(MessageBox.Show);