开发者

Issue with reading a xml file

开发者 https://www.devze.com 2023-01-11 04:36 出处:网络
I\'m having a problem with reading and processing a xml file, which I cannot solve right now. The xml has the following structure:

I'm having a problem with reading and processing a xml file, which I cannot solve right now. The xml has the following structure:

<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");

Unfortunately, "currentlyselectedtestnode.SelectSingleNode("//a")" will read out all "a"-nodes and not only the one that bel开发者_开发百科ongs to test-node with id 1. Why ?! Somehow currentlyselectedtestnode.SelectSingleNode("//a"); works just as if I wrote Doc.SelectSingleNode("//a");

How come ?! How can I make it read the children of the specific test-node only ?ectedtestnode.SelectSingleNode("//c");


When using //a in XPath, you are selecting all a nodes in the document.

If you want the direct child, you need to use currentlyselectedtestnode.SelectSingleNode("a").

See XPath Syntax on w3schools:

// - Selects nodes in the document from the current node that match the selection no matter where they are

You can select all a nodes that are under the current node by using .//a. This will select all child a nodes of the current node, regardless of how deeply nested they are.

0

精彩评论

暂无评论...
验证码 换一张
取 消