使用 Xpath 找到共同的父母 [英] find common parent using Xpath
问题描述
我想知道是否有任何方法可以使用 Xpath 访问公共父节点.
I was wondering if there was any way to access common parent node using Xpath.
<outer>
<main>
<a><b> sometext </b></a>
<c><d> sometext2 </d></c>
</main>
</outer>
我有文本节点 sometext 和 sometext2.有没有办法可以访问这两个节点的主(公共父)?我不知道包含这些节点的 xml 的布局.
I have the text nodes sometext and sometext2. is there a way i can access main (common parent) of these two nodes? I do not know the layout of the xml containing these nodes.
推荐答案
使用以下 XPath 1.0 表达式:
$v1/ancestor::*
[count(. | $v2/ancestor::*)
=
count($v2/ancestor::*)
]
[1]
其中 $v1 和 $v2 包含两个文本节点(如果您使用的 XPath 不在 XSLT 中,则必须将上述表达式中的 $v1 和 $v2 替换为选择这两个文本节点中的每一个).
where $v1 and $v2 hold the two text nodes (in case you use XPath not within XSLT, you will have to replace $v1 and $v2 in the above expression with the XPath expressions that select each one of these two text nodes).
说明:
上述 XPath 1.0 表达式查找两个节点集的交集:$v1 的所有元素祖先的节点集和 $v2 的所有元素祖先的节点集.这是通过所谓的 Kaysian 交集方法完成的(以 Michael Kay 的名字命名,他于 2000 年发现了这一点).使用Kaysian方法进行交集,通过以下XPath表达式选择两个节点集$ns1和$ns2的交集:
The above XPath 1.0 expression finds the intersection of two node-sets: the node-set of all element ancestors of $v1 and the node-set of all element ancestors of $v2. This is done with the so called Kaysian method for intersection (after Michael Kay, who discovered this in 2000). Using the Kaysian method for intersection, the intersection of two nodesets, $ns1 and $ns2 is selected by the following XPath expression:
$ns1[count(. | $ns2) = count($ns2)]
然后,从祖先的交集我们必须选择最后一个元素.但是,因为我们使用的是反向轴(祖先),所以所需的节点位置必须表示为 1.
通过应用以下转换,可以快速验证上述 XPath 表达式是否确实选择了最低的公共祖先:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:variable name="v1" select="/*/*/a/b/text()"/>
<xsl:variable name="v2" select="/*/*/c/d/text()"/>
<xsl:variable name="vCommonAncestor" select=
"$v1/ancestor::*
[count(. | $v2/ancestor::*)
=
count($v2/ancestor::*)
]
[1]"
/>
<xsl:template match="/">
<xsl:value-of select="name($vCommonAncestor)"/>
</xsl:template>
</xsl:stylesheet>
应用于最初提供的 XML 文档时(更正为格式良好的 XML):
when applied on the originally-provided XML document (corrected to well-formed XML):
<outer>
<main>
<a>
<b>sometext</b>
</a>
<c>
<d>sometext2</d>
</c>
</main>
</outer>
想要的结果(两个文本节点的最低共同祖先元素的名称)产生:
the wanted result (the name of the element that is the lowest common ancestor of the two text nodes) is produced:
主要
选择两个节点的最低公共祖先的 XPath 2.0 表达式更简单,因为它使用了标准的 XPath 2.0 运算符intersect":
The XPath 2.0 expression that selects the lowest common ancestor of the two nodes is simpler, because it uses the standard XPath 2.0 operator "intersect":
($v1/ancestor::* intersect $v2/ancestor::*)
[last()]
这篇关于使用 Xpath 找到共同的父母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!