XPath 查找具有特定子节点的所有元素 [英] XPath find all elements with specific child node

查看:59
本文介绍了XPath 查找具有特定子节点的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能帮我找出下面例子中所有带有子元素c的元素b吗?

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

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

xpath 查询必须返回 b2 元素

The xpath query must return the b2 element

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

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]

推荐答案

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

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:

/*/b[c]

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

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

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

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

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

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]

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

The provided XPath expression does select exactly the wanted element.

这是基于 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>

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

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

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

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

这篇关于XPath 查找具有特定子节点的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆