首页 > 解决方案 > 有没有更好的方法来访问我的 XML 文档中的子节点?

问题描述

这是我的 XmlDocument

<?xml version="1.0"?>
<Config>
  <Path1></Path1>
  <Path2></Path2>
  <Path3></Path3>
  <Path4></Path4>
  <Path5></Path5>
  <PdfMenu>
    <PdfDocument Attribute1="1" Attribute2="1.1" Attribute3="1.2" Attribute4="1.3" Attribute5="1.4" />
    <PdfDocument Attribute1="2" Attribute2="2.1" Attribute3="2.2" Attribute4="2.3" Attribute5="2.4" />
    <PdfDocument Attribute1="3" Attribute2="3.1" Attribute3="3.2" Attribute4="3.3" Attribute5="3.4" />
  </PdfMenu>
</Config>

我目前正在使用它来解决节点<PdfMenu>

foreach (XmlNode n in xmlDoc.ChildNodes.Item(1).ChildNodes.Item(5).ChildNodes)

现在,每次我添加另一个时,<Path>我都必须调整Item数字。有没有更好的方法来做到这一点?

标签: c#xmlxmldocument

解决方案


最好使用 LINQ to XML API。它在 .Net 框架中可用超过 10 年。

Descendants()无论 XML 中有多少其他元素,该方法都会直接访问您需要的元素。

C#

void Main()
{
    XDocument xdoc = XDocument.Parse(@"<Config>
    <Path1></Path1>
    <Path2></Path2>
    <Path3></Path3>
    <Path4></Path4>
    <Path5></Path5>
    <PdfMenu>
        <PdfDocument Attribute1='1' Attribute2='1.1' Attribute3='1.2'
                     Attribute4='1.3' Attribute5='1.4'/>
        <PdfDocument Attribute1='2' Attribute2='2.1' Attribute3='2.2'
                     Attribute4='2.3' Attribute5='2.4'/>
        <PdfDocument Attribute1='3' Attribute2='3.1' Attribute3='3.2'
                     Attribute4='3.3' Attribute5='3.4'/>
    </PdfMenu>
</Config>");

    foreach (var element in xdoc.Descendants("PdfDocument"))
    {
        Console.WriteLine(element);
    }
}

推荐阅读