有没有更好的方法来访问我的 XML 文档中的子节点?

Is there a better way to access the ChildNodes in my XML Document?

这是我的 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 数字。有更好的方法吗?

最好用LINQ来XML API。在 .Net 框架中已有 10 多年的历史。

无论 XML.

中有多少其他元素,Descendants() 方法直接转到您需要的元素

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

可以使用 SelectNodes() 获取所有 PdfDocument 节点。如果 xpath 以双正斜杠 // 开头,它会告诉代码获取(以下节点的)所有实例。

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(@"<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 xmlDoc.SelectNodes("//PdfDocument"))
{
    Console.WriteLine(element);
}

这确实是实现解决方案的老方法。 @Yitzhak Khabinsky 的 LINQ to XML API 解决方案是更优选的方式 .