xml XPath 查找具有特定子节点的所有元素

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

XPath find all elements with specific child node

xmlxpath

提问by nam

Could you please help me to find all the elements b which have the child element c in the example below?

你能帮我在下面的例子中找到所有具有子元素 c 的元素 b 吗?

<a>
    <b name = "b1"></b>
    <b name = "b2"><c/></b>
    <b name = "b3"></b>
</a>

The xpath query must return the b2 element

xpath 查询必须返回 b2 元素

The second question is I want to combine 2 conditions: I want to get the element which have name = "b2" and has the element c But this syntax seems not to work: //b[@name='b2' and c]

第二个问题是我想结合两个条件:我想得到 name = "b2" 并且有元素 c 的元素但是这个语法似乎不起作用://b[@name='b2' and c]

回答by Dimitre Novatchev

Whenever the structure of the XML document is known, it is better to avoid using the //XPath pseudo-operator, as its use can result in big inefficiency (traversal of the whole document tree).

只要知道 XML 文档的结构,最好避免使用//XPath 伪运算符,因为它的使用会导致效率低下(遍历整个文档树)。

Therefore, I recomment this XPath expression for the provided XML document:

因此,我为所提供的 XML 文档推荐此 XPath 表达式:

/*/b[c]

This selects any belement that is a child of the top element of the XML document and that has a child-element named c.

这将选择b作为 XML 文档顶部元素的子元素并且具有名为 的子元素的任何元素c

UPDATE: The OP asked a second question just minutes ago:

更新:OP 几分钟前问了第二个问题:

The second question is I want to combine 2 conditions: I want to get the element which have name = "b2" and has the element c But this syntax seems not to work: //b[@name='b2' and c]

第二个问题是我想结合两个条件:我想获得 name = "b2" 并且有元素 c 的元素但是这个语法似乎不起作用: //b[@name='b2' and c]

The provided XPath expression doesselect exactly the wanted element.

提供的 XPath 表达式确实选择了所需的元素。

Here is XSLT - based verification:

这是基于 XSLT 的验证

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="/*">
     <xsl:copy-of select="//b[@name='b2' and c]"/>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the provided XML document:

当此转换应用于提供的 XML 文档时:

<a>
    <b name = "b1"></b>
    <b name = "b2"><c/></b>
    <b name = "b3"></b>
</a>

the XPath expression is evaluated and the correctly-selected element is copied to the output:

计算 XPath 表达式并将正确选择的元素复制到输出:

<b name="b2">
   <c/>
</b>

回答by choroba

It should be as simple as

应该很简单

//b[c]

i.e. find a banywhere that has a cchild.

即找到一个bc孩子的地方。