XPath可以只返回具有X子节点的节点吗?

Rya*_*lle 34 xml xslt xpath

是否可以使用XPath仅选择具有特定子元素的节点?例如,从这个XML我只想要宠物中有'bar'子元素的元素.因此,结果数据集将包含此示例中的lizardpig元素:

<pets>
  <cat>
    <foo>don't care about this</foo>
  </cat>
  <dog>
   <foo>not this one either</foo>
  </dog>
  <lizard>
   <bar>lizard should be returned, because it has a child of bar</bar>
  </lizard>
  <pig>
   <bar>return pig, too</bar>
  </pig>
</pets>
Run Code Online (Sandbox Code Playgroud)

这个Xpath给了我所有的宠物:"/pets/*",但我只想要有一个名字的子节点的宠物'bar'.

Chr*_*org 49

这就是它的荣耀

/pets/*[bar]
Run Code Online (Sandbox Code Playgroud)

英语:给我所有pets有孩子的孩子bar


小智 23

/pets/child::*[child::bar]
Run Code Online (Sandbox Code Playgroud)

我的原谅,我没有看到对上一个答复的评论.

但在这种情况下,我宁愿使用descendant::轴,其中包括指定的所有元素:

/pets[descendant::bar]
Run Code Online (Sandbox Code Playgroud)


Hir*_*ter 5

以防万一您想更具体地了解孩子 - 您也可以对他们使用选择器。

例子:

<pets>
    <cat>
        <foo>don't care about this</foo>
    </cat>
    <dog>
        <foo>not this one either</foo>
    </dog>
    <lizard>
        <bar att="baz">lizard should be returned, because it has a child of bar</bar>
    </lizard>
    <pig>
        <bar>don't return pig - it has no att=bar </bar>
    </pig>
</pets>
Run Code Online (Sandbox Code Playgroud)

现在,您只关心所有pets具有valuebar 属性的attbaz孩子。您可以使用以下 xpath 表达式:

//pets/*[descendant::bar[@att='baz']]
Run Code Online (Sandbox Code Playgroud)

结果

<lizard>
    <bar att="baz">lizard should be returned, because it has a child of bar</bar>
</lizard>
Run Code Online (Sandbox Code Playgroud)