Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlNode.SelectSingleNode returns element outside current?

Tags:

c#

xml

xpath

my problem is like this. Let's say i have xml like this

<root>
  <child Name = "child1">
    <element1>Value1</element1>
    <element2>Value2</element2>
  </child>
  <child Name = "child2">
    <element1>Value1</element1>
    <element2>Value2</element2>
    <element3>Value3</element3>
  </child>
</root>

I have a method that gets as parameter XmlNode "node". Lets say "node" has value "child1" Then i try like this:

node.SelectSingleNode( "//element3" );

The problem is this code returns element3 from "child2". What i want is if there is no child "element3" of "node" to return null so i add it by hand.
Best Regards,
Iordand

like image 683
IordanTanev Avatar asked Feb 10 '10 15:02

IordanTanev


4 Answers

The XPath expression you have isn't what you want.

Replace it with this:

node.SelectSingleNode( "element3" ); 

And you'll get the result you're looking for.

like image 134
Welbog Avatar answered Oct 19 '22 12:10

Welbog


The following work perfect when i want to run xpath on the specified node.

XmlNodeList nodes = xmlDoc.SelectNodes(".//Child");
like image 36
kazim Avatar answered Oct 19 '22 12:10

kazim


The "//" is a global look up.

What you'll need to do is get a list of all children

XmlNodeList nodes = xmlDoc.SelectNodes("//Child");

loop through that list and do a

XmlNode node = nodes.SelectSingleNode("element3");

This will return null if it's not there, and will step through every child looking.

like image 8
taylonr Avatar answered Oct 19 '22 14:10

taylonr


the problem here is the XPath expression you are using, try it without the '//'. Like that:

node.SelectSingleNode( "element3" );

Read more here .

like image 3
Alexander Vakrilov Avatar answered Oct 19 '22 13:10

Alexander Vakrilov