3

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>
4

2 回答 2

6

XPath//是一种缩写语法,用于从文档根目录中选择任何后代。//ns:x将选择ns:x文档中的每一个——它不以它的父节点为根——所以使用它SelectSingleNode总是会选择ns:x文档中的第一个。

如果您将 XPath 更改为 simple ns:x,它将只选择child ns:x,它应该可以工作。

实际上,您可以通过将第一个 XPath 调用修改为 select 来摆脱第二个 XPath 调用//ns:pits/ns:x[1],这将选择文档ns:x中 every 的第一个子项。ns:pits

于 2013-09-05T03:57:03.597 回答
3

用这个:

XmlNode x = pit.SelectSingleNode(".//ns:x", nsmgr);

注意.前面的点 ( )//ns:x

于 2014-06-16T13:47:52.940 回答