37

是否可以使用 XPath 仅选择具有特定子元素的节点?例如,从这个 XML 中,我只想要 pets 中具有“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>

这个 Xpath 给了我所有的 pets: "/pets/*",但我只想要具有 name 子节点的 pets 'bar'

4

3 回答 3

55

在这里,它的所有荣耀

/pets/*[bar]

pets把所有有孩子的孩子都给我bar

于 2008-09-19T21:06:27.463 回答
26
/pets/child::*[child::bar]

对不起,我没有看到上一个回复的评论。

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

/pets[descendant::bar]
于 2009-01-11T17:20:01.440 回答
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>

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

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

结果

<lizard>
    <bar att="baz">lizard should be returned, because it has a child of bar</bar>
</lizard>
于 2014-09-10T14:50:02.280 回答