0

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.

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by mvujica
0

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

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.