xslt - 有什么方法可以在 XSLT 中生成计数器值?

标签 xslt

当它们不存在时,有没有办法使用 XSLT 生成唯一 ID(顺序很好)?我有以下几点:

<xsl:template match="Foo">
   <xsl:variable name="varName">
      <xsl:call-template name="getVarName">
         <xsl:with-param name="name" select="@name"/>
      </xsl:call-template>
   </xsl:variable>
   <xsl:value-of select="$varName"/> = <xsl:value-of select="@value"/>
</xsl:template>

<xsl:template name="getVarName">
   <xsl:param name="name" select="''"/>
   <xsl:choose>
      <xsl:when test="string-length($name) > 0">
         <xsl:value-of select="$name"/>
      </xsl:when>
      <xsl:otherwise>
         <xsl:text>someUniqueID</xsl:text> <!-- Stuck here -->
      </xsl:otherwise>
   </xsl:choose>
</xsl:template>

输入如下内容:
<Foo name="item1" value="100"/>
<Foo name="item2" value="200"/>
<Foo value="300"/>

我希望能够分配一个唯一的值,以便我最终得到:
item1 = 100
item2 = 200
unnamed1 = 300

最佳答案

首先,当您调用模板时上下文节点不会更改,您不需要在您的情况下传递参数。

<xsl:template match="Foo">
   <xsl:variable name="varName">
      <xsl:call-template name="getVarName" />
   </xsl:variable>
   <xsl:value-of select="$varName"/> = <xsl:value-of select="@value"/>
</xsl:template>

<xsl:template name="getVarName">
   <xsl:choose>
      <xsl:when test="@name != ''">
         <xsl:value-of select="@name"/>
      </xsl:when>
      <xsl:otherwise>
         <!-- position() is sequential and  unique to the batch -->
         <xsl:value-of select="concat('unnamed', position())" />
      </xsl:otherwise>
   </xsl:choose>
</xsl:template>

也许这就是你现在所需要的。但是,未命名节点的输出不会严格按顺序编号(unnamed1、unnamed2 等)。你会得到这个:

项目 1 = 100
项目 2 = 200
未命名3 = 300

关于xslt - 有什么方法可以在 XSLT 中生成计数器值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2291809/

相关文章:

xslt - 使用 XSLT 向标签添加属性

xml - XSLT 中的秒数

xml - 使用XPath从RSS feed中选择前5个元素

java - 用 Java 处理 XSLT?

delphi - 阻止 XSLT 转换将 utf-8 XML 转换为 utf-16?

XSLT 1.0 如何递增日期

xslt - 如何向 XSLT for-each 语句添加多个过滤器?

html - 在 ie9 和 ie10 中转换相同的 xsl 文件会产生不同的 html

java - XPATH表达式输出父节点和匹配的子节点,排除不匹配的子节点

java - java中html的xsl转换