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

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

这个Xpath给了我所有宠物:&quot; / pets / *&quot; ,但我只想要一个名为'bar'的子节点的宠物。

有帮助吗?

解决方案

这就是它的荣耀

/pets/*[bar]

英语:给我所有 pets 的孩子,他们有一个孩子 bar

其他提示

/pets/child::*[child::bar]

我的原谅,我没有看到对上一次回复的评论。

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

/pets[descendant::bar]

万一你想要更具体地了解孩子 - 你也可以在他们身上使用选择器。

示例:

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

现在,您只关心所有具有 att 的子 bar pets att ,其值为 baz 即可。您可以使用以下xpath表达式:

//pets/*[descendant::bar[@att='baz']]

结果

<lizard>
    <bar att="baz">lizard should be returned, because it has a child of bar</bar>
</lizard>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top