This has a very simple and short solution - no recursion, no parameters, no xsl:element , no xsl:attribute :
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="div"> <span class="level{count(ancestor::*)}"> <xsl:value-of select="concat(@type, ' ', @n)"/> </span> <xsl:apply-templates/> </xsl:template> </xsl:stylesheet>
when this conversion is applied to the provided XML document :
<text> <div type="Book" n="3"> <div type="Chapter" n="6"> <div type="Verse" n="12"></div></div></div> </text>
required, the correct result is obtained :
<span class="level1">Book 3</span> <span class="level2">Chapter 6</span> <span class="level3">Verse 12</span>
The explanation . Proper use of templates, AVT and count() .
Dimitre novatchev
source share