XSLT 2.0 提供了将节点集参数作为 position() 函数的一部分进行传递的优势。不幸的是,这在 XSLT 1.0 中不可用。有没有办法模仿这种行为?
例如,给定这个 XML:
<wishlists>
<wishlist name="Games">
<product name="Crash Bandicoot"/>
<product name="Super Mario Brothers"/>
<product name="Sonic the Hedgehog"/>
</wishlist>
<wishlist name="Movies">
<product name="Back to the Future"/>
</wishlist>
</wishlists>
和这个 XSLT 2.0:
<xsl:value-of select="position(/wishlists/wishlist/product)"/>
在处理最后的“回到 future ”节点时,将返回值“4”。
不幸的是,我似乎能够使用 XSLT 1.0 获得的最接近结果如下:
<xsl:template match="product">
<xsl:value-of select="position()"/>
</xsl:template>
但是,我会在同一个“回到 future ”节点中得到值“1”,而不是我真正想要的值“4”。
最佳答案
您可以使用 preceding axis .
这个 XSLT 1.0 样式表:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="product">
<product position="{count(preceding::product) + 1}">
<xsl:apply-templates select="@*"/>
</product>
</xsl:template>
</xsl:stylesheet>
应用于您的 XML 输入会产生:
<wishlists>
<wishlist name="Games">
<product position="1" name="Crash Bandicoot"/>
<product position="2" name="Super Mario Brothers"/>
<product position="3" name="Sonic the Hedgehog"/>
</wishlist>
<wishlist name="Movies">
<product position="4" name="Back to the Future"/>
</wishlist>
</wishlists>
关于xml - 模仿 XSLT 1.0 中的位置(节点集)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9397608/