Re: [xsl] Dynamic numbering of lists in xslt

Subject: Re: [xsl] Dynamic numbering of lists in xslt
From: Abel Braaksma <abel.online@xxxxxxxxx>
Date: Tue, 09 Jan 2007 18:00:52 +0100
David Carlisle wrote:

<xsl:number /> <!-- will only count the matches consecutively -->

Nope, it will number according to the input tree (but the advice to use templates rather than a xsl:choose stricture is good)

You are right, of course. Using position(), you can change this behavior through the apply-templates. Using the input from the OP, and my approach, the following is a way to do it (using xslt 2 for ease of use and not needing an input doc, call it on itself)


<xsl:stylesheet
version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform";>
<xsl:output indent="yes"/>
<xsl:variable name="source">
<chapter1>
<section>first section</section>
</chapter1>
<chapter1>
<section>second section</section>
</chapter1>
<chapter1>
<section>third section</section>
</chapter1>
<chapter1>
<section>fourth section</section>
</chapter1>
</xsl:variable>


<xsl:template match="/">
<xsl:apply-templates
select="$source/chapter1[not(section = 'second section')]" />
</xsl:template>
<xsl:template match="chapter1">
<chap>
<xsl:value-of select="concat(position(), '. ', section)" />
</chap>
</xsl:template>
</xsl:stylesheet>


Output:
<chap>1. first section</chap>
<chap>2. third section</chap>
<chap>3. fourth section</chap>


However, if the select-statement becomes more complex, other approaches may be better (not meaning xsl:choose). In addition, if XSLT 2.0 were an option, the select-attribute could be used to achieve the same goal.


If Saxon extensions can be used, an easy (but unwanted) quick fix is to use saxon's assignable variables.

-- Abel

Current Thread