代码之家  ›  专栏  ›  技术社区  ›  Jon

有没有办法在XSLT中生成一个计数器值?

  •  2
  • Jon  · 技术社区  · 16 年前

    当它们不存在时,是否有任何方法可以使用XSLT生成唯一ID(顺序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
    
    4 回复  |  直到 16 年前
        1
  •  2
  •   Tomalak    16 年前

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

    <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>
    

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

    item1 = 100
    item2 = 200
    unnamed3 = 300
    
        2
  •  1
  •   GSerg    16 年前

    generate-id 函数会起作用吗?

        3
  •  0
  •   AxelEckenberger    16 年前
        4
  •  0
  •   Dmitry Tashkinov    16 年前

    尝试这样的操作,而不是使用模板:

    <xsl:template match="/DocumentRootElement">
    <xsl:for-each select="Foo">
      <xsl:variable name="varName">
        <xsl:choose>
          <xsl:when test="string-length(@name) > 0">
            <xsl:value-of select="@name"/>
          </xsl:when>
          <xsl:otherwise>unnamed<xsl:value-of select="position()"/></xsl:otherwise>
        </xsl:choose>
      </xsl:variable>
      <xsl:value-of select="$varName"/> = <xsl:value-of select="@value"/>\r\n
    </xsl:for-each>