读取xml文件时出现问题

时间:2010-08-13 09:11:32

标签: c# asp.net xml

我在阅读和处理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");

不幸的是,“currentselectedtestnode.SelectSingleNode(”// a“)”将读出所有“a”节点,而不仅仅是属于id为1的测试节点的节点。为什么?! 不知怎的,当前选择了testnode.SelectSingleNode(“// a”);就像我写了Doc.SelectSingleNode(“// a”);

一样

怎么来的?!我怎样才能让它只读取特定测试节点的子节点?ectedtestnode.SelectSingleNode(“// c”);

1 个答案:

答案 0 :(得分:5)

在XPath中使用//a时,您正在选择文档中的所有 a个节点。

如果您想要直接孩子,则需要使用currentlyselectedtestnode.SelectSingleNode("a")

请参阅w3schools上的XPath Syntax

  

// - 从当前节点中选择与选择匹配的文档中的节点,无论它们位于何处

您可以使用a选择当前节点下的所有.//a个节点。这将选择当前节点的所有a节点,无论它们的嵌套程度如何。

相关问题