xml - for-each 中的计数器,position() 没有用

标签 xml xslt

如何在 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-eachapply-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/

相关文章:

c# - 根级别的数据无效。第 1 行,位置 1,写作时

java - 有没有一个java库可以将XML(LOM)绑定(bind)到XML+RDF?

java - 通过 XSLT 将 XML 节点中的 HTML 转义为 XSL-FO

xml - 将 XML 文件导入 SQL Server 太慢

xml - XSL : position() in template match vs position() in select

python - 类型错误 : iter() takes no keyword arguments

java - 使用 jcabi 将参数传递给 XSL 文件

javascript - XSL 中的空元素 - 嵌套问题

xslt - 如何将以数字开头的字符串转换为 XSLT 中的数字数据?

Javascript - 解析 XML 文档以创建数组