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.

Recommended Answers

All 2 Replies

This is should be close to what you want.

<?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>

Thank you, it is a straightforward solution, I should have looked deeper into XPATH reference.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.