[英]Relative XPath selection using XmlNode (c#)
Say i have the following xml file: 假设我有以下xml文件:
<a>
<b>
<c></c>
</b>
<b>
<c></c>
</b>
</a>
var nodes = doc.SelectNodes("/a/b");
will select the two b nodes. 将选择两个b节点。
I then loop these two nodes suchas: 然后我循环这两个节点,例如:
foreach (XmlNode node in nodes) { }
However, when i call node.SelectNodes("/a/b/c");
但是,当我调用node.SelectNodes("/a/b/c");
It still returns both values and not just the descendants. 它仍然返回两个值,而不仅仅是后代。 Is it possible to select nodes only descening from the current node
? 是否可以选择仅从当前node
下降的node
?
在foreach
循环中,您已经知道该node
是原始文档中的/a/b
- 因此只需使用相对 xpath就可以得到它的 c
子node
:
node.SelectNodes("c")
你可以使用node.SelectSingleNode("C");
/a/b[1]/c
For intance gets the nodelist of all the children of the first b that have the tagname c. 对于intance,获取具有标记名c的第一个b的所有子节点的节点列表。
To get the first c as a singleton nodelist use /a/b[1]/c[1]. 要将第一个c作为单个节点列表,请使用/ a / b [1] / c [1]。 /a/b/c[1] again returns a nodelist of multiple nodes. / a / b / c [1]再次返回多个节点的节点列表。
SelectSingleNode is probably misleading, as far as I know, XPath always returns a nodelist, which can contain optionally one node (or even be empty). SelectSingleNode可能会产生误导,据我所知,XPath总是返回一个nodelist,它可以包含一个节点(甚至可以是空的)。
//c[1] just selects the first c in the document. // c [1]只选择文档中的第一个c。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.