在 XPath 1.0 中,实现此目的的一种方法是使用 Kayessian 方法进行节点集交集:
$ns1[count(.|$ns2) = count($ns2)]
上面的表达式精确选择属于节点集的节点$ns1
和节点集$ns2
.
将此应用于具体问题-- 假设我们需要选择第二个和第三个之间的所有节点h3
以下 XML 文档中的元素:
<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
with:
/*/h3[2]/following-sibling::node()
并替换$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 解决方案:
Use the intersect
操作员:
/*/h3[2]/following-sibling::node()
intersect
/*/h3[3]/preceding-sibling::node()