在 XSLT 1.0 中,假设当前节点是 a div
:
.//spec[generate-id(current())=generate-id(ancestor::div[1])]
在相同假设下的 XSLT 2.0 中:
.//spec[ancestor::div[1] is current()]
还有一个纯 XPath 2.0 表达式:
for $this in .
return
$this//spec[ancestor::div[1] is $this]
完整的 XSLT 1.0 转换:
<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="div">
<div n="{@n}"/>
<xsl:copy-of select=
".//spec[generate-id(current())=generate-id(ancestor::div[1])]"/>
==============
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
应用于提供的 XML 文档时:
<div n="a">
. . .
. . .
<spec>red</spec>
<spec>green</spec>
. . .
<div n="b">
. . .
<spec>blue</spec>
. . .
</div>
<div n="c">
<spec>yellow</spec>
</div>
. . .
. . .
. . .
</div>
产生了想要的正确结果:
<div n="a"/>
<spec>red</spec>
<spec>green</spec>
==============
<div n="b"/>
<spec>blue</spec>
==============
<div n="c"/>
<spec>yellow</spec>
==============
完整的 XSLT 2.0 转换:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="div">
<div n="{@n}"/>
<xsl:sequence select=".//spec[ancestor::div[1] is current()]"/>
===================================
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
当应用于同一个 XML 文档(上图)时,会产生相同的正确结果:
<div n="a"/>
<spec>red</spec>
<spec>green</spec>
===================================
<div n="b"/>
<spec>blue</spec>
===================================
<div n="c"/>
<spec>yellow</spec>
===================================
并使用纯 XPath 2.0(否current()
):
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="div">
<div n="{@n}"/>
<xsl:sequence select="
for $this in .
return
$this//spec[ancestor::div[1] is $this]"/>
===================================
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
产生相同的正确结果:
<div n="a"/>
<spec>red</spec>
<spec>green</spec>
===================================
<div n="b"/>
<spec>blue</spec>
===================================
<div n="c"/>
<spec>yellow</spec>
===================================