tags:

views:

95

answers:

1

If I call SelectNodes on an XmlElement, and pass XPath query such as this:

XmlNodeList nodes = xmlElement.SelectNodes("//OtherNode");

The nodes list will be for all the OtherNode elements in the document not just the ones from xmlElement.

I seem to recall that this is by design, and for a good reason, but I can't remember what that good reason was, nor how to get around it.

+2  A: 

Just add a dot to the beginning of the xpath. The dot selects the current node:

XmlNodeList nodes = xmlElement.SelectNodes(".//OtherNode");
bruno conde
A simple explanation of "why" is that it's like with file paths - `/foo/bar` is an absolute path, where the leading `/` means "start from root"; `foo/bar` is a relative file path, which can also be written `./foo/bar`. Similarly with XPath, and there it applies to both `/` and `//` - so leading `/` always means "start from root node in the tree to which the current context node belongs".
Pavel Minaev
Why not just "OtherNode"?
Joren
Because he wants to consider all descendants, and not just immediate children?
Pavel Minaev