如何在 XSLT 中不使用 position() 而使用计数器? 例如: XML
<product type="A" name="pepe"/>
<product type="B" name="paco"/>
<product type="A" name="Juan"/>
<product type="B" name="Edu"/>
<product type="A" name="Lauren"/>
我想按编号顺序显示所有类型“A”:
1.pepe
2.Juan
3.Lauren
xsl 就是这样的
<xsl:for-each select="./products">
<xsl:if test="./products/product/@type="A"">
<tr>
<xsl:value-of select="position()"/>
<xsl:value-of select="./product/@name"/>
</tr>
</xsl:if>
</xsl:for-each>
最佳答案
position()
函数是上下文相关的 - 它为您提供当前节点在“当前节点列表”中的位置,即 select< 提取的节点列表
当前 for-each
或 apply-templates
的表达式。所以如果你做类似的事情
<xsl:for-each select="product">
<xsl:if test="@type = 'A'">
<li><xsl:value-of select="position()"/>: <xsl:value-of select="@name" /></li>
</xsl:if>
</xsl:for-each>
然后您将获得 position()
值 1、3 和 5,因为 select
选择了所有五个产品元素。但是,如果您将 @type
测试放在 select
表达式中:
<xsl:for-each select="product[@type = 'A']">
<li><xsl:value-of select="position()"/>: <xsl:value-of select="@name" /></li>
</xsl:for-each>
然后您将获得位置 1、2 和 3,因为 for-each
仅处理 @type
为 A 的三个产品元素,而不是所有五个他们。
在更复杂的情况下,您确实确实需要处理所有 product
元素(例如,如果您正在使用类型 A 和类型 B 不同的东西,但需要保持文档顺序)然后你需要用 preceding-sibling::
轴做一个技巧,例如
<xsl:if test="@type = 'A'">
<xsl:value-of select="count(preceding-sibling::product[@type = 'A']) + 1" />
</xsl:if>
明确计算与此具有相同 @type
的前面 product
元素的数量。
关于xml - for-each 中的计数器,position() 没有用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18449453/