如何使用xslt生成唯一和随机的字符串,以便将其关联到标记的属性。例如,我想在这个标签上添加一个唯一的id。
<generalization xmi:id="unique ID">发布于 2015-05-12 22:10:51
可以使用generate-id()创建唯一标识符。引用标准,“此函数返回唯一标识给定节点的字符串。”
考虑一下这个样式表:
<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- Replace <xyzzy> with <generalization xml:id="unique ID"> -->
<xsl:template match="xyzzy">
<generalization>
<xsl:apply-templates select="@*"/>
<xsl:attribute name="xml:id"><xsl:value-of select="generate-id()"/></xsl:attribute>
<xsl:apply-templates/>
</generalization>
</xsl:template>
<!-- Copy everything else straight thru -->
<xsl:template match="node( ) | @*">
<xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
</xsl:template>
</xsl:stylesheet>适用于这一投入:
<?xml version='1.0' encoding='ASCII'?>
<root>
<xyzzy/>
<xyzzy a="b">
<xyzzy xml:id="non-unique-id"/>
</xyzzy>
</root>有了这个结果:
<?xml version="1.0"?>
<root>
<generalization xml:id="idp28972496"/>
<generalization a="b" xml:id="idp28945920">
<generalization xml:id="idp28946416"/>
</generalization>
</root>注意生成-id()的值在整个文档中是如何唯一的。
发布于 2017-04-20 13:40:16
可以在临时XML节点上使用generate()来创建任意长度的随机字符串:
<!-- language: lang-xml -->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:kh="https://github.com/kohsah"
exclude-result-prefixes="xs xd"
version="2.0">
<xsl:function name="kh:shortRandom">
<xsl:variable name="mxml">
<node/>
</xsl:variable>
<xsl:sequence select="generate-id($mxml//node)"/>
</xsl:function>
<xsl:function name="kh:longRandom">
<xsl:sequence select="concat(kh:shortRandom(), kh:shortRandom(), kh:shortRandom(), kh:shortRandom())"></xsl:sequence>
</xsl:function>
<xsl:template match="/">
<test>
<randomId><xsl:value-of select="kh:shortRandom()"/></randomId>
<guid><xsl:value-of select="kh:longRandom()"/></guid>
</test>
</xsl:template>
</xsl:stylesheet>这里有两个XSL函数:
kh:shortRandom(),它生成4个字母的随机字符串,如这个:"d2e1“kh:longRandom():"d3e1d4e1d5e1d6e1“https://stackoverflow.com/questions/30195871
复制相似问题