XPath以选择具有指定名称的所有元素 [英] XPath to select all elements with a specified name

查看:47
本文介绍了XPath以选择具有指定名称的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为,仅使用标准XPath即可解决此问题,而无需参考实现,但仅供参考,我使用的是.Net(System.Xml命名空间)中的XML DOM对象.

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).

我有一个从XML文档深处的某个地方移交给我的函数的节点,并且我希望选择该节点所有具有特定名称的后代元素,而不管这些节点的中间路径如何.我正在拨打的电话看起来像这样:

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:

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>
...

我想要的是所有苹果"节点的列表,即3个结果.我尝试了几种不同的方法,但是都没有得到我想要的.

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.

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

这给了我数百个结果,看起来像文档中的每个Apple节点,或者至少是文档根目录的直接子节点的每个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.

我如何创建一个XPath,该XPath将为我提供当前节点下的所有apple节点,而不管它们在当前节点下的深度如何?具体来说,根据上面的示例,我应该得到三个结果-红色,绿色和黄色的苹果.

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.

推荐答案

尝试 .//apple .此列表列出了作为当前节点后代的所有 apple 节点.为了更好地理解该主题,您应该学习XPath轴如何工作.例如,您还可以编写 descendant :: apple .

Try .//apple. This lists all the apple nodes 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.

这篇关于XPath以选择具有指定名称的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆