Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random and unique string xslt

Tags:

xml

xslt

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">
like image 546
Iheb Avatar asked Sep 08 '25 01:09

Iheb


1 Answers

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.

like image 117
Robᵩ Avatar answered Sep 10 '25 14:09

Robᵩ