Numbering Textual Output

Problem

You want to create sequentially numbered output.

Solution

Since output can be numbered in many ways, this example presents a series of increasingly complex examples that address the most common (and a few uncommon) numbering needs.

Number siblings sequentially

This category is the simplest form of numbering. For example, you can produce a numbered list of people using the stylesheet in Example 5-35 and Example 5-36.

Example 5-35. Stylesheet

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>
   
  <xsl:template match="person">
    <xsl:number count="*" format="1. "/> 
    <xsl:value-of select="@name"/>
  </xsl:template>
   
</xsl:stylesheet>

Example 5-36. Output

1. Al Zehtooney
2. Brad York
3. Charles Xavier
4. David Willimas
5. Edward Ulster
6. Frank Townsend
7. Greg Sutter
8. Harry Rogers
9. John Quincy
10. Kent Peterson
...

You can use the justify template discussed in Recipe 5.3 if you want right-justified numbers.

Start from a number other than one

xsl:number does not provide a standard facility for starting from or incrementing by a number other than one, but you can handle this task with a little math. Example 5-37 and Example 5-38 start from ten and increment by five, just to be different.

Example 5-37. Stylesheet using nonsequential numbering

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:strip-space elements="*"/> <xsl:template match="person"> ...

Get XSLT Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.