您将如何使用 XPATH 查找两个 H3 之间的所有节点? [英] How would you find all nodes between two H3's using XPATH?
本文介绍了您将如何使用 XPATH 查找两个 H3 之间的所有节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用 XPATH 查找两个 H3 之间的所有节点?
How would you find all nodes between two H3's using XPATH?
推荐答案
在 XPath 1.0 中,一种方法是使用 Kayessian 方法进行节点集交集:
$ns1[count(.|$ns2) = count($ns2)]
上面的表达式精确地选择了同时属于节点集 $ns1
和节点集 $ns2
的节点.
The above expression selects exactly the nodes that are part both of the node-set $ns1
and the node-set $ns2
.
要将其应用于特定问题 -- 假设我们需要选择以下 XML 文档中第 2 个和第 3 个 h3
元素之间的所有节点:
To apply this to the specific question -- let's say we need to select all nodes between the 2nd and 3rd h3
element in the following XML document:
<html>
<h3>Title T31</h3>
<a31/>
<b31/>
<h3>Title T32</h3>
<a32/>
<b32/>
<h3>Title T33</h3>
<a33/>
<b33/>
<h3>Title T34</h3>
<a34/>
<b34/>
<h3>Title T35</h3>
</html>
我们必须用代替$ns1
:
/*/h3[2]/following-sibling::node()
并将$ns2
替换为:
and to substitute $ns2
with:
/*/h3[3]/preceding-sibling::node()
因此,完整的 XPath 表达式为:
/*/h3[2]/following-sibling::node()
[count(.|/*/h3[3]/preceding-sibling::node())
=
count(/*/h3[3]/preceding-sibling::node())
]
我们可以验证这是正确的 XPath 表达式:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<xsl:copy-of select=
"/*/h3[2]/following-sibling::node()
[count(.|/*/h3[3]/preceding-sibling::node())
=
count(/*/h3[3]/preceding-sibling::node())
]
"/>
</xsl:template>
</xsl:stylesheet>
当这个转换应用于上面显示的 XML 文档时,会产生想要的、正确的结果:
<a32/>
<b32/>
<小时>
二.XPath 2.0 解决方案:
使用intersect
运算符:
Use the intersect
operator:
/*/h3[2]/following-sibling::node()
intersect
/*/h3[3]/preceding-sibling::node()
这篇关于您将如何使用 XPATH 查找两个 H3 之间的所有节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文