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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/105613/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 12:03:35  来源:igfitidea点击:

Can XPath return only nodes that have a child of X?

xmlxsltxpath

提问by Ryan Stille

Is it possible to use XPath to select only the nodes that have a particular child elements? For example, from this XML I only want the elements in pets that have a child of 'bar'. So the resulting dataset would contain the lizardand pigelements from this example:

是否可以使用 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>

This Xpath gives me all pets: "/pets/*", but I only want the pets that have a child node of name 'bar'.

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

回答by Chris Marasti-Georg

Here it is, in all its glory

在这里,在它所有的荣耀中

/pets/*[bar]

English: Give me all children of petsthat have a child bar

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

回答by Ryan Stille

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

My pardon, I did not see the comments to the previous reply.

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

But in this case I'd rather prefer using the descendant::axis, which includes all elements down from specified:

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

/pets[descendant::bar]

回答by Hirnhamster

Just in case you wanted to be more specific about the children - you can also use selectors on them.

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

Example:

例子:

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

Now, you only care about all petshaving any child barthat has an attribute attwith value baz. You can use the following xpath expression:

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

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

Result

结果

<lizard>
    <bar att="baz">lizard should be returned, because it has a child of bar</bar>
</lizard>