add element unique Id XSLT
-
I am quite new to XSLT and I want to add unique index to elements types to transform something like this:
<item1>
<item2>
<item3></item3>
<item3></item3>
</item2>
<item2>
<item3></item3>
<item3></item3>
</item2>
</item1>
<item1>
</item1>into:
<item1 id="1">
<item2 id="1">
<item3 id="1"></item3>
<item3 id="2"></item3>
</item2>
<item2 id="2">
<item3 id="3"></item3>
<item3 id="4"></item3>
</item2>
</item1>
<item1 id="2">
</item1>I tried using position() but it counts based on context and not globally on document. Thanx. :^)
-
I am quite new to XSLT and I want to add unique index to elements types to transform something like this:
<item1>
<item2>
<item3></item3>
<item3></item3>
</item2>
<item2>
<item3></item3>
<item3></item3>
</item2>
</item1>
<item1>
</item1>into:
<item1 id="1">
<item2 id="1">
<item3 id="1"></item3>
<item3 id="2"></item3>
</item2>
<item2 id="2">
<item3 id="3"></item3>
<item3 id="4"></item3>
</item2>
</item1>
<item1 id="2">
</item1>I tried using position() but it counts based on context and not globally on document. Thanx. :^)
I have got the answer from daniweb (thanks fpmurphy) :
-
<?xml version="1.0"?>
-
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
-
<xsl:output method="xml" indent="yes"/>
-
<xsl:template match="/">
-
<xsl:apply-templates/>
-
</xsl:template>
-
<xsl:template match="\*">
-
<xsl:variable name="name" select="name()" />
-
<xsl:element name="{name()}">
-
<xsl:attribute name="id">
-
<xsl:value-of select="count(preceding::\*\[name()=$name\]) + 1" />
-
</xsl:attribute>
-
<xsl:apply-templates />
-
</xsl:element>
-
</xsl:template>
-
</xsl:stylesheet>
-