Take the following XML as example:
<root>
<lines>
<line>
<number>1</number>
</line>
<line>
<number>2</number>
</line>
</lines>
</root>
XmlNodeList nodeList = doc.SelectNodes("//lines/line");
foreach(XmlNode node in nodeList)
{
int index = node.SelectSingleNode("//number");
}
The above code will result in index = 1 for both iterations.
foreach(XmlNode node in nodeList)
{
int index = node.SelectSingleNode("number");
}
The above code will result in 1,2 respectively. I know that // finds first occurrence of xpath but i feel like the first occurrence should be relative to the node itself. The behavior appears to find first occurrence from the root even when selecting nodes from a child node. Is this the way microsoft intended this to work or is this a bug.
Removing the slashes only works because
number
is an immediate child element ofline
. If it were further down in the hierarchy:you would still need to use
.//number
.That's just how XPath syntax is designed.
//
at the beginning of an XPath expression means that the evaluation context is the document node - the outermost node of an XML document..//
means that the context of the path expression is the current context node.If you think about it, it is actually useful to have a way to select from the whole document in any context.
Microsoft is implementing the XPath standard, and yes, this is how the W3C intended an XPath library to work and it's not a bug.