How to generate unique id contains numeric value only of length 8 digits using XSLT

时间:2018-08-22 13:53:05

标签: xslt

I want to generate unique id that contains numeric only using XSLT. The unique id should be of length 8 digits. I do not want to use any Java namespace to generate this unique id. I have found one solution using Java namespace that having math.random() function. but in my case Java namespace will not work because I am generating output through Saxon processor using C#.

Please provide some solution to generate unique id having lenth 8 digits only without using Java namespace in XSLT.

1 个答案:

答案 0 :(得分:1)

如果您接受“连续” ID(连续数字),则可以使用xsl:number

示例脚本:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="@*|node()">
    <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
  </xsl:template>  

  <xsl:template match="*">
    <xsl:copy>
      <xsl:attribute name="id">
        <xsl:number level="any" count="*" format="99999999"/>
      </xsl:attribute>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

有关xsl:number的详细信息:

  • count="*"导致所有元素都被计数,
  • level="any"来自任何嵌套级别,
  • format="99999999"以所需的格式(8位数字)。

如果仍然不清楚,请阅读有关xsl:number的信息。