Reputation: 25938
I am parsing some XML. I am iterating over 2 Pit
nodes and trying to find out their x
node value.
My problem: When I inspect each Pit
nodes x
value its always says value is 8
, when the second nodes x
value is actually 1
.
Why is this happening and how can I fix it?
XmlNodeList xNodes = xdoc.DocumentElement.SelectNodes("//ns:pits", nsmgr);
foreach (XmlNode pit in xNodes) {
XmlNode x = pit.SelectSingleNode("//ns:x", nsmgr);
MessageBox.Show(x.InnerText, ""); // Always prints "8", when 1 should be "8", another "1"
}
The data I am using:
<?xml version="1.0"?>
<xml12d>
<pit>
<x>8.89268569</x>
<y>1.26122586</y>
<z>1.62414621</z>
</pit>
<pit>
<x>1.09268598</x>
<y>7.24091243</y>
<z>8.20896044</z>
</pit>
</xml12d>
Upvotes: 4
Views: 985
Reputation: 31
Use this:
XmlNode x = pit.SelectSingleNode(".//ns:x", nsmgr);
Notice the dot (.
) before //ns:x
Upvotes: 3
Reputation: 30031
The XPath //
is an abbreviated syntax to select any descendant from the document root. //ns:x
will select every ns:x
in the document -- it isn't scoped to its parent node as a root -- so using it with SelectSingleNode
will always select the first ns:x
in the document.
If you change the XPath to simply ns:x
, which will select only child ns:x
, it should work.
You can actually get rid of the second XPath call by modifying the first to select //ns:pits/ns:x[1]
, which will select the first ns:x
child of every ns:pits
in the document.
Upvotes: 6