2

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

Chris M
  • 182
  • 2
  • 4
  • 17

3 Answers3

6
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); 
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
1

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

You want: root/set[2]

annakata
  • 74,572
  • 17
  • 113
  • 180
1

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);
R Dragon
  • 981
  • 8
  • 9