2010-02-18 27 views
2

有没有什么办法可以在XSLT不存在时使用XSLT生成唯一的ID(顺序很好)?我有以下几点:任何方式在XSLT中生成计数器值?

<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 

回答

2

首先,上下文节点没有,当你调用模板改变,你不需要传递参数在情况。

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

也许这就是你现在需要的全部。虽然,未命名节点的输出不会被严格按顺序编号(未命名1,未命名2等)。你会得到这个:

 
item1 = 100 
item2 = 200 
unnamed3 = 300 
+0

这工作很好,谢谢! – Jon 2010-02-23 19:50:08

1

也许将自己的常量前缀附加到generate-id函数的结果中会有诀窍吗?

0

尝试这样的事情,而不是你的模板:

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