【问题标题】:XSLT generate UUIDXSLT 生成 UUID
【发布时间】:2011-11-14 19:29:50
【问题描述】:

如何使用纯 XSLT 生成 UUID?基本上是在寻找一种使用 XSLT 创建独特序列的方法。序列可以是任意长度。

我正在使用 XSLT 2.0。

【问题讨论】:

标签: xslt uuid


【解决方案1】:

这是good example。基本上你设置了一个指向 java UUID 类的扩展,然后在 XSL 中引用它:

<xsl:stylesheet version="2.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:uuid="java:java.util.UUID">
<xsl:template match="/">
  <xsl:variable name="uid" select="uuid:randomUUID()"/>
  <xsl:value-of select="$uid"/>
</xsl:template>

【讨论】:

  • 对不起,没有澄清。我之前确实看过那个例子,但它需要在纯 XSLT 中完成。没有 Java。
  • 我赞成,因为这对我有用。然而,值得注意的是,像这样的自反 Java 调用也不适用于 Saxon HE 许可证(尽管正如其他人所指出的,编写自己的函数来实现它或多或少是一个已解决的问题)。
  • PS - 没关系 xsl:stylesheet/xsl:value-of 无效,如果没有关闭 xsl:stylesheet 标记,它甚至都不是很好的格式;) - 我相信我们都可以弄清楚什么是意思是!
【解决方案2】:

您可以为此使用 xslt sn-p(来源:http://code.google.com/p/public-contracts-ontology/source/browse/transformers/GB-notices/uuid.xslt?r=66e1d39a1c140079a86d219df5b3e031007cc957):

<xsl:stylesheet xmlns:uuid="http://www.uuid.org" xmlns:math="http://exslt.org/math" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

        <xsl:template match="/">
                <xsl:value-of select="
concat('First random ID:', uuid:get-id()),
concat('Base timestamp: ', uuid:generate-timestamp()),
concat('Clock id: ' ,uuid:generate-clock-id()),
concat('Network node: ' ,uuid:get-network-node()),
concat('UUID Version: ' ,uuid:get-uuid-version()),
concat('Generated UUID: ' ,uuid:get-uuid()),
concat('Generated UUID: ' ,uuid:get-uuid()),
concat('Generated UUID: ' ,uuid:get-uuid()),
concat('Generated UUID: ' ,uuid:get-uuid())
" separator="&#10;"/>
        </xsl:template>

    <!--
Functions in the uuid: namespace are used to calculate a UUID
The method used is a derived timestamp method, which is explained
here: http://www.famkruithof.net/guid-uuid-timebased.html
and here: http://www.ietf.org/rfc/rfc4122.txt
-->
    <!--
Returns the UUID
-->
    <xsl:function name="uuid:get-uuid" as="xs:string*">
        <xsl:variable name="ts" select="uuid:ts-to-hex(uuid:generate-timestamp())"/>
        <xsl:value-of separator="-" select="
            substring($ts, 8, 8),
            substring($ts, 4, 4),
            string-join((uuid:get-uuid-version(), substring($ts, 1, 3)), ''),
            uuid:generate-clock-id(),
            uuid:get-network-node()"/>
    </xsl:function>
    <!--
internal aux. fu
with saxon, this creates a more-unique result with
generate-id then when just using a variable containing a node
-->
    <xsl:function name="uuid:_get-node">
        <xsl:comment/>
    </xsl:function>
    <!-- generates some kind of unique id -->
    <xsl:function name="uuid:get-id" as="xs:string">
        <xsl:sequence select="generate-id(uuid:_get-node())"/>
    </xsl:function>
    <!--
should return the next nr in sequence, but this can't be done
in xslt. Instead, it returns a guaranteed unique number
-->
    <xsl:function name="uuid:next-nr" as="xs:integer">
        <xsl:variable name="node">
            <xsl:comment/>
        </xsl:variable>
        <xsl:sequence select="
            xs:integer(replace(
            generate-id($node), '\D', ''))"/>
    </xsl:function>
    <!-- internal fu for returning hex digits only -->
    <xsl:function name="uuid:_hex-only" as="xs:string">
        <xsl:param name="string"/>
        <xsl:param name="count"/>
        <xsl:sequence select="
            substring(replace(
            $string, '[^0-9a-fA-F]', '')
            , 1, $count)"/>
    </xsl:function>
    <!-- may as well be defined as returning the same seq each time -->
    <xsl:variable name="_clock" select="uuid:get-id()"/>
    <xsl:function name="uuid:generate-clock-id" as="xs:string">
        <xsl:sequence select="uuid:_hex-only($_clock, 4)"/>
    </xsl:function>
    <!--
returns the network node, this one is 'random', but must
be the same within calls. The least-significant bit must be '1'
when it is not a real MAC address (in this case it is set to '1')
-->
    <xsl:function name="uuid:get-network-node" as="xs:string">
        <xsl:sequence select="uuid:_hex-only('09-17-3F-13-E4-C5', 12)"/>
    </xsl:function>
    <!-- returns version, for timestamp uuids, this is "1" -->
    <xsl:function name="uuid:get-uuid-version" as="xs:string">
        <xsl:sequence select="'1'"/>
    </xsl:function>
    <!--
Generates a timestamp of the amount of 100 nanosecond
intervals from 15 October 1582, in UTC time.
-->
    <xsl:function name="uuid:generate-timestamp">
        <!--
date calculation automatically goes
correct when you add the timezone information, in this
case that is UTC.
-->
        <xsl:variable name="duration-from-1582" as="xs:dayTimeDuration">
            <xsl:sequence select="
                current-dateTime() -
                xs:dateTime('1582-10-15T00:00:00.000Z')"/>
        </xsl:variable>
        <xsl:variable name="random-offset" as="xs:integer">
            <xsl:sequence select="uuid:next-nr() mod 10000"/>
        </xsl:variable>
        <!-- do the math to get the 100 nano second intervals -->
        <xsl:sequence select="
            (days-from-duration($duration-from-1582) * 24 * 60 * 60 +
            hours-from-duration($duration-from-1582) * 60 * 60 +
            minutes-from-duration($duration-from-1582) * 60 +
            seconds-from-duration($duration-from-1582)) * 1000
            * 10000 + $random-offset"/>
    </xsl:function>
    <!-- simple non-generalized function to convert from timestamp to hex -->
    <xsl:function name="uuid:ts-to-hex">
        <xsl:param name="dec-val"/>
        <xsl:value-of separator="" select="
            for $i in 1 to 15
            return (0 to 9, tokenize('A B C D E F', ' '))
            [
            $dec-val idiv
            xs:integer(math:power(16, 15 - $i))
            mod 16 + 1
            ]"/>
    </xsl:function>
    <xsl:function name="math:power">
        <xsl:param name="base"/>
        <xsl:param name="power"/>
        <xsl:choose>
            <xsl:when test="$power &lt; 0 or contains(string($power), '.')">
                <xsl:message terminate="yes">

                    The XSLT template math:power doesn't support negative or

                    fractional arguments.

                </xsl:message>
                <xsl:text>NaN</xsl:text>
            </xsl:when>
            <xsl:otherwise>
                <xsl:call-template name="math:_power">
                    <xsl:with-param name="base" select="$base"/>
                    <xsl:with-param name="power" select="$power"/>
                    <xsl:with-param name="result" select="1"/>
                </xsl:call-template>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:function>
    <xsl:template name="math:_power">
        <xsl:param name="base"/>
        <xsl:param name="power"/>
        <xsl:param name="result"/>
        <xsl:choose>
            <xsl:when test="$power = 0">
                <xsl:value-of select="$result"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:call-template name="math:_power">
                    <xsl:with-param name="base" select="$base"/>
                    <xsl:with-param name="power" select="$power - 1"/>
                    <xsl:with-param name="result" select="$result * $base"/>
                </xsl:call-template>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
</xsl:stylesheet>:choose>
    </xsl:template>
</xsl:stylesheet>

【讨论】:

  • 感谢分享。源(公共合同本体)是一个死链接:(
  • 使用此代码可以获得 4 个不同的 UUID "": 23CD00A6 -8952-11E6-2114-09173F13E4C5 23CD00A5-8952-11E6-2114-09173F13E4C5 23CD00A3-8952-11E6-2114-09173F13E4C5 23CD00A4-8952-11E6-2114C54-09E
  • 但是使用 "”:382967A6-8952-11E6-2114-09173F13E4C5 382967A5-8952-11E6-2114 -09173F13E4C5 382967A3-8952-11E6-2114-09173F13E4C5 382967A4-8952-11E6-2114-09173F13E4C5 382967A6-8952-11E6-2114-09173F13E4C5 382967A5-8952-11E6-2114-09173F13E4C5 382967A3-8952-11E6-2114-09173F13E4C5 382967A4-8952 -11E6-2114-09173F13E4C5 知道如何使用“xls:for-each”获取新的 UUID?
  • 使用:&lt;xsl:for-each select="uuid:get-uuid()"&gt;&lt;xsl:attribute name="Test" select="."/&gt;&lt;/xsl:for-each&gt; 在 for-each 循环中获取唯一值
【解决方案3】:

这是在纯 XPath 2 或更高版本中执行此操作的最简单和最短的方法

unparsed-text("https://uuidgen.org/api/v/4")

如果您想生成多个 GUID,比如 100 个,请执行以下操作:

for $i in 1 to 100
  return unparsed-text(concat("https://uuidgen.org/api/v/4?x=", $i))

说明

因为标准 XSLT 2.0 / XPath 3.0(和更高版本)函数 unparsed-text()deterministic,它必须在每次调用时使用相同的参数返回相同的结果。因此,兼容的 XPath 实现必须缓存第一个响应,并且从此以后只为相同的参数生成缓存的响应。

为避免这种情况,我们为每个调用生成一个略有不同的 URL,从而使 XPath 规范作者的努力徒劳无功。

享受

【讨论】:

  • @user:4099593:请取消删除另一个答案并删除这个答案。我们至少可以在这里链接到未删除的答案吗?这将对读者有所帮助。感谢您的理解
  • @bhargav-rao,请取消删除另一个答案并删除这个答案。我们至少可以在这里链接到未删除的答案吗?这将对读者有所帮助。感谢您的理解
【解决方案4】:

由于 XSLT 是一种函数式语言,生成随机数不是该语言的一部分。也就是说,有一些扩展包 (EXSLT) 和一些处理器 (Saxon) 支持生成随机数。如果您不能使用扩展程序或 Saxon,那么我相信您不走运。

【讨论】:

【解决方案5】:

看看另一个问题Generate GUID in XSLT

this 的文章可能会对您有所帮助 - 那里定义了 XSLT 函数来生成 GUID

【讨论】:

    【解决方案6】:

    有关在 XSLT 中生成随机数的信息,请参阅 Casting the Dice with FXSL: Random Number Generation Functions in XSLT。它使用的唯一扩展函数是 node-set(),在 XSLT 2.0 中不再需要它。

    另外,如果只要求 ID 是唯一的(不一定是随机的),请查看 how to generate unique string。例如,如果您要为输入 XML 文档的每个元素生成 UUID,则可以使用输入文档的 URL 和 &lt;xsl:number&gt; 的组合为每个元素生成唯一的字符串。

    【讨论】:

      【解决方案7】:

      如果使用.NetXslCompiledTransform来转换你的XSL,你可以将EnableScripts属性设置为true,然后使用如下代码:

      <msxsl:script language="C#" implements-prefix="csharp">
          <![CDATA[
          public static string NewGuid()
          {
              return Guid.NewGuid().ToString();
          }
          ]]>
      </msxsl:script>
      

      注意:我在上面为这个自定义功能指定了名称/前缀csharp;但你可以随意称呼它。

      有关启用脚本的更多信息,请参阅https://stackoverflow.com/a/1873265/361842

      下面的完整 XSLT 文件提供了一些额外的上下文:

      <?xml version="1.0" encoding="utf-8"?>
      <xsl:stylesheet 
          version="1.0" 
          xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
          xmlns:msxsl="urn:schemas-microsoft-com:xslt"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:csharp="urn:JohnLBevan/NewGuid"
          exclude-result-prefixes="xsl msxsl csharp"
      >
      
          <xsl:template match="@* | node()">
              <xsl:copy>
                  <xsl:apply-templates select="@* | node()"/>
              </xsl:copy>
          </xsl:template>
      
          <xsl:template match="//*/text()">
              <!-- replaces all text nodes from input document with GUIDs -->
              <xsl:value-of select="csharp:NewGuid()"/>
          </xsl:template>
      
          <msxsl:script language="C#" implements-prefix="csharp">
              <![CDATA[
              public static string NewGuid()
              {
                  return Guid.NewGuid().ToString();
              }
              ]]>
          </msxsl:script>
      
      </xsl:stylesheet>
      

      【讨论】:

        猜你喜欢
        • 2018-11-15
        • 1970-01-01
        • 2016-10-23
        • 2017-06-25
        • 2013-11-16
        • 1970-01-01
        • 1970-01-01
        • 2016-02-25
        • 1970-01-01
        相关资源
        最近更新 更多