Search code examples
c#xmlxmldocument

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


This is my 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>

I am currently using this to address the Nodes in <PdfMenu>

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

Right now, every time I add another <Path> I have to adjust the Item Number. Is there a better way to do that?


Solution

  • It's possible to fetch all PdfDocument nodes by using SelectNodes(). If the xpath starts with double forwardslash //, it tells the code to fetch all instances (of the following node).

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

    This is really the old way of achieving the solution. The LINQ to XML API solutions by @Yitzhak Khabinsky is the more preferred way.