[英]XPath expression to select all nodes
I would like to find all <Field />
nodes (that may be arbitrarily nested) inside a given XmlNode. 我想在给定的XmlNode中找到所有<Field />
节点(可以任意嵌套)。
If do something like this: 如果执行以下操作:
foreach(XmlNode n in node.SelectNodes('//Field'))...
This returns all nodes in the entire document, not all nodes under node
. 这将返回整个文档中的所有节点,而不是node下的所有node
。
Is this how XPath is supposed to work? 这是XPath应该如何工作的吗? I looked at some documents and it seems like the //Node
query should be scoped to whatever node it's invoked at. 我查看了一些文档,似乎//Node
查询的作用域应为调用它的任何节点。
Is there any other technique to select all nodes with a given name that are under a specific node? 是否有其他技术可以选择特定节点下具有给定名称的所有节点?
If you use '//Field'
it's absolut from the root of the document. 如果您使用'//Field'
则它是从文档根目录开始的绝对值。 To search relative to the current node, just use './/Field'
. 要相对于当前节点进行搜索,只需使用'.//Field'
。
尝试使用SelecteSingleNode()
Use ./Field
. 使用./Field
。
.//
Means descendants, which includes children of children (and so forth). .//
后代,其中包括孩子的孩子(依此类推)。 ./
Means direct children. ./
直系子女。 If a XPath starts with a /
it becomes relative to the root of the document; 如果XPath以/
开头,则它相对于文档的根目录; to make it relative to your own node start it with ./
. 使它相对于您自己的节点以./
开头。
You can use simple linq query like this: 您可以使用简单的linq查询,如下所示:
var techLeads = (from value in element.Descendants ("Manager")
where value.Attribute ("Name").Value == "Mgr1"
select value).Descendants("TechLead");
Sample Xml: 样本Xml:
<Employees> <Manager Name="Mgr1"> <TechLead Name="TL1" /> <TechLead Name="TL2" /> </Manager> </Employees>
删除//
因为否则它将在所有文档中搜索到根节点。
node.SelectNodes("Field")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.