Chris M
Chris M

Reputation: 242

Need help selecting the second child node and it's children with XPath in C#

I'm trying to select the second child node off the root and all it's children from XML that looks similar to this:

<root>
   <SET>
      <element>
      <element>
   </SET>
   <SET>
      <element>
      <element>
   </SET>
<root>

I'm after all the tags in the second node, any help would be greatly appreciated!

I'm using C#. I tried the XPath /SET[1] however that didn't see to help!

Many thanks!

C

Upvotes: 2

Views: 12695

Answers (3)

R Dragon
R Dragon

Reputation: 991

Below is my solution:

XmlDocument doc = new XmlDocument();

doc.Load(@"C:\testing.xml");

XmlNodeList sets = doc.GetElementsByTagName("SET");

//Show the value of first set's first element
Console.WriteLine(sets[0].ChildNodes[0].InnerText);

//Show the value of second set's second element
Console.WriteLine(sets[1].ChildNodes[1].InnerText);

Upvotes: 1

Pranay Rana
Pranay Rana

Reputation: 176956

x/y[1] : 
     The first <y> child of each <x>. This is equivalent to the expression in the next row.

x/y[position() = 1] :The first <y> child of each <x>.

Try this :

string xpath = "/root/set[2]";
XmlNode locationNode = doc.SelectSingleNode(xpath); 

or

string xpath = "/root/set[position() = 2]";
XmlNode locationNode = doc.SelectSingleNode(xpath); 

Upvotes: 6

annakata
annakata

Reputation: 75872

XPath is not zero-index based, it's one-indexed.

You want: root/set[2]

Upvotes: 1

Related Questions