.net XPath 选择具有指定名称的所有元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15077462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XPath to select all elements with a specified name
提问by Sean Worle
I believe this should be able to be answered just using standard XPath without reference to implementation, but just for reference I am using the XML DOM objects in .Net (System.Xml namespace).
我相信这应该可以仅使用标准 XPath 来回答,而无需参考实现,但仅供参考,我正在使用 .Net(System.Xml 命名空间)中的 XML DOM 对象。
I have a node handed to my function, from somewhere deep inside an XML document, and I want to select all descendant elements of this node that have a specific name, regardless of the intervening path to those nodes. The call I'm making looks like this:
我有一个节点从 XML 文档深处的某个地方传递给我的函数,我想选择该节点的所有具有特定名称的后代元素,而不管这些节点的中间路径如何。我打的电话是这样的:
node.SelectNodes("some XPath here");
The node I'm working with looks something like this:
我正在使用的节点如下所示:
...
<food>
<tart>
<apple color="yellow"/>
</tart>
<pie>
<crust quality="flaky"/>
<filling>
<apple color="red"/>
</filling>
</pie>
<apple color="green"/>
</food>
...
What I want is a list of all of the "apple" nodes, i.e. 3 results. I've tried a couple of different things, but none of them get what I want.
我想要的是所有“苹果”节点的列表,即 3 个结果。我尝试了几种不同的方法,但没有一个得到我想要的。
node.SelectNodes("apple");
This gives me one result, the green apple.
这给了我一个结果,青苹果。
node.SelectNodes("*/apple");
This gives me one result, the yellow apple.
这给了我一个结果,黄色的苹果。
node.SelectNodes("//apple");
This gives me hundreds of results, looks like every apple node in the document, or at least maybe every apple node that is a direct child of the root of the document.
这给了我数百个结果,看起来像文档中的每个苹果节点,或者至少每个苹果节点都是文档根的直接子节点。
How do I create an XPath that will give me all the apple nodes under my current node, regardless of how deep under the current node they are found? Specifically, based on my example above, I should get three results - the red, green, and yellow apples.
如何创建一个 XPath 来为我提供当前节点下的所有苹果节点,而不管它们在当前节点下有多深?具体来说,根据我上面的例子,我应该得到三个结果——红苹果、绿苹果和黄苹果。
回答by nwellnhof
Try .//apple. This lists all the applenodes that are descendants of the current node. For a better understanding of this topic, you should learn how XPath axes work. You could also write descendant::apple, for example.
试试.//apple。这列出apple了作为当前节点的后代的所有节点。为了更好地理解该主题,您应该了解 XPath 轴的工作原理。descendant::apple例如,您也可以编写。

