How can I generate a unique and random string with xslt in order to associate it to an attribute of a tag. for eg I want to add a unique id to this tag
<generalization xmi:id="unique ID">
You can use generate-id()
to create unique identifiers. To quote the standard, "This function returns a string that uniquely identifies a given node."
Consider this stylesheet:
<?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>
applied to this input:
<?xml version='1.0' encoding='ASCII'?>
<root>
<xyzzy/>
<xyzzy a="b">
<xyzzy xml:id="non-unique-id"/>
</xyzzy>
</root>
With this result:
<?xml version="1.0"?>
<root>
<generalization xml:id="idp28972496"/>
<generalization a="b" xml:id="idp28945920">
<generalization xml:id="idp28946416"/>
</generalization>
</root>
Notice how the value of generate-id() is unique across the document.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With