CPU
CPU

Reputation: 91

Iterate over child nodes in an XML document

I have the following xml file structure:

<configuration>
 <Points>
    <Point1>
      <Url>net.tcp://10.1.1.144</Url>
      <Domain>10.1.1.144</Domain>
      <Secure>true</Secure>
      <UserName>flofy</UserName>
      <Password>Jojo</Password>
    </Point1>

    <Point2>
      <Url>net.tcp://10.1.1.22</Url>
      <Domain>10.1.1.22</Domain>
      <Secure>false</Secure>
      <UserName></UserName>
      <Password></Password>
    </Point2>
 </Points>
</configuration>

I want to iterate over all the ponts, I tried:

var doc = new XmlDocument();
doc.Load(@"C:\myXml.xml");
var nodes = doc.DocumentElement.SelectNodes("/configuration/Points");
foreach (XmlNode n in nodes)
{
    MessageBox.Show(n.Name);
}

But it prints only Points, but I want it to print Point1, Point2 etc..

Upvotes: 4

Views: 2598

Answers (1)

marsze
marsze

Reputation: 17164

You want to do..

foreach (XmlNode n in doc.SelectSingleNode("/configuration/Points").ChildNodes)
{
    MessageBox.Show(n.Name);
}

Your xpath query does only select the node "Points", but you want to iterate its child nodes.

Upvotes: 3

Related Questions