Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper XPath for "all nodes exactly one below the base node?"

Tags:

c#

xml

xpath

Presuming that I don't know the name of my base node or its children, what is the XPath syntax for "all nodes exactly one below the base node?"

With pattern being an XmlNode, I have the following code:

XmlNodeList kvpsList = pattern.SelectNodes(@"//");

Which looks right to me, but I get the following exception:

   System.Xml.XPath.XPathException: Expression must evaluate to a node-set.

What is the correct syntax?

like image 852
Yes - that Jake. Avatar asked Mar 27 '09 19:03

Yes - that Jake.


2 Answers

The path you're looking for is

/*/*

// isn't a meaningful XPath expression, since it is an operator. If you wrote something like //element, it would match every element named element anywhere in the XML document, no matter how deep into the hierarchy it is.

/*/* is saying "match every node that has two levels of depth in the hierarchy".

like image 124
Welbog Avatar answered Nov 02 '22 23:11

Welbog


The two current answers are wrong:

/*/*

does not select all nodes that are children of the top node. It does not select any text nodes, processing-instructions or comments that are children of the top element.

One XPath expression that select all nodes that arte children of the top element is:

/*/node()

// is not a syntactically correct XPath expression; according to the XPath Spec:

// is short for /descendant-or-self::node()/

Do note the beginning of an unfinished location step at the very end of the expanded abbreviation. If nothing is added to it, the whole XPath expression containing the abbreviation is finished and, therefore, syntactically incorrect.

Another note is that the // abbreviation is not necessary in specifying the selection of all nodes that are children of the top element. If you wanted to select all nodes in the XML document that descend from the top element, then one XPath expression that select these is:

/*//node()

like image 22
Dimitre Novatchev Avatar answered Nov 03 '22 01:11

Dimitre Novatchev