“Tojio Labs is the place where little useful insights (and unimportant ones) from our everyday work as an interactive agency found their home.”

Unique ID for each node in an XML file [en]

Well this is just a little, everyday task: I’m currently working on the Sto International Website and needed to modify an XML file so that each of its nodes has a unique ID assigned. The fastest way to achieve this is a very simple XSL transformation like the one below:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    <xsl:output method="xml" indent="yes" />
    <!--
        This stylesheet just assigns a unique ID
        to each node in the XML tree
    -->
    <xsl:template match="/">
        <xsl:apply-templates />
    </xsl:template>
    <xsl:template match="*">
        <xsl:element name=" { name ( ) } ">
            <xsl:attribute name="nodeID">
                <xsl:value-of select="generate-id ( ) " />
            </xsl:attribute>
            <!-- copy any other attributes -->
            <xsl:for-each select="attribute::*">
                <xsl:copy />
            </xsl:for-each>
                <!-- and do everything recursively -->
            <xsl:apply-templates />
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>


You can use fairly any XSLT processor you want to let it do the job. In my case (Mac OS X), I just did it on the command line with xsltproc (Syntax: -o output-file.xml stylesheet.xsl input-file.xml):

Xor:sto02 gertz$ xsltproc -o out.xml idmaker.xsl input.xml

No Comments, Comment or Ping

Comments are closed.


senseless guy