Dim*_*hev 28
在XPath 1.0中,一种方法是使用Kayessian方法进行节点集交集:
$ns1[count(.|$ns2) = count($ns2)]
Run Code Online (Sandbox Code Playgroud)
上面的表达式精确地选择了属于节点集$ns1和节点集的节点$ns2.
要将此应用于特定问题 - 假设我们需要h3在以下XML文档中选择第2和第3个元素之间的所有节点:
<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>
Run Code Online (Sandbox Code Playgroud)
我们必须替换$ns1为:
/*/h3[2]/following-sibling::node()
Run Code Online (Sandbox Code Playgroud)
并替换为$ns2与:
/*/h3[3]/preceding-sibling::node()
Run Code Online (Sandbox Code Playgroud)
因此,完整的XPath表达式是:
/*/h3[2]/following-sibling::node()
[count(.|/*/h3[3]/preceding-sibling::node())
=
count(/*/h3[3]/preceding-sibling::node())
]
Run Code Online (Sandbox Code Playgroud)
我们可以验证这是正确的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>
Run Code Online (Sandbox Code Playgroud)
当此转换应用于上面提供的XML文档时,将生成所需的正确结果:
<a32/>
<b32/>
Run Code Online (Sandbox Code Playgroud)
II.XPath 2.0解决方案:
使用intersect运营商:
/*/h3[2]/following-sibling::node()
intersect
/*/h3[3]/preceding-sibling::node()
Run Code Online (Sandbox Code Playgroud)
小智 7
当你知道两个标记是相同的元素时,其他XPath 1.0解决方案(本例h3):
/html/body/h3[2]/following-sibling::node()
[not(self::h3)]
[count(preceding-sibling::h3)=2]
Run Code Online (Sandbox Code Playgroud)