我在读取和处理 xml 文件时遇到问题,我现在无法解决。 xml 具有以下结构:
<root>
<test id="1">
<a></a>
<b></b>
<c></c>
</test>
<test id="2">
<a></a>
<b></b>
<c></c>
</test>
<test id="3">
<a></a>
<b></b>
<c></c>
</test>
</root>
XmlDocument Doc; int currentid=1;
XmlNode currentlyselectedtestnode =
Doc.SelectNodes("//test[@id = '" +
currentid.ToString() + "']");
string a = currentlyselectedtestnode.SelectSingleNode("//a");
string b = currentlyselectedtestnode.SelectSingleNode("//b");
string c = currentlyselectedtestnode.SelectSingleNode("//c");
不幸的是,“currentlyselectedtestnode.SelectSingleNode("//a")”将读出所有“a”节点,而不仅仅是属于 id 为 1 的测试节点。为什么?! 不知何故 currentlyselectedtestnode.SelectSingleNode("//a");就像我写的一样工作 Doc.SelectSingleNode("//a");
怎么会?!我怎样才能让它只读取特定测试节点的子节点?ectedtestnode.SelectSingleNode("//c");
最佳答案
在 XPath 中使用 //a
时,您选择了文档中的所有 a
节点。
如果你想要直接 child ,你需要使用currentlyselectedtestnode.SelectSingleNode("a")
。
参见 XPath Syntax在 w3schools 上:
//
- Selects nodes in the document from the current node that match the selection no matter where they are
您可以使用.//a
选择当前 节点下的所有a
节点。这将选择当前节点的所有 a
子节点,无论它们嵌套的深度如何。
关于c# - 读取 xml 文件的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3475421/