XSLT - What is <xsl:number>

<xsl:number> is used when you need automatic numbering in XSLT (like generating chapter numbers, ordered lists, or hierarchical numbering).


What is <xsl:number>?

  • It outputs a number (or sequence of numbers) based on the position of the current node in the source XML tree.

  • Very flexible: can generate simple numbers (1,2,3…), Roman numerals (I, II, III…), letters (a, b, c…), or hierarchical numbers (1.1.1).


Syntax

<xsl:number 
    level="single|multiple|any"
    count="pattern"
    from="pattern"
    value="expression"
    format="format-string"/>

Main attributes

  • level

    • single → number relative to closest ancestor/parent (default).

    • multiple → hierarchical numbering (like 1.1, 1.2.1).

    • any → counts across the whole document.

  • count → which elements to count (pattern).

  • from → where to start counting from.

  • value → explicitly set the number instead of auto-counting.

  • format → output style (1, 01, a, A, i, I, etc).


Example 1: Simple numbering

XML

<chapters>
    <chapter>Introduction</chapter>
    <chapter>Getting Started</chapter>
    <chapter>Advanced Topics</chapter>
</chapters>

XSLT

<xsl:template match="/">
  <html>
    <body>
      <h2>Chapters</h2>
      <ul>
        <xsl:for-each select="chapters/chapter">
          <li>
            <xsl:number/>. <xsl:value-of select="."/>
          </li>
        </xsl:for-each>
      </ul>
    </body>
  </html>
</xsl:template>

Output

<ul>
  <li>1. Introduction</li>
  <li>2. Getting Started</li>
  <li>3. Advanced Topics</li>
</ul>

Example 2: Hierarchical numbering

XML

<book>
    <chapter>
        <title>Introduction</title>
        <section>Overview</section>
        <section>History</section>
    </chapter>
    <chapter>
        <title>Advanced</title>
        <section>Details</section>
    </chapter>
</book>

XSLT

<!-- Number chapters -->
<xsl:template match="chapter">
  <h2>
    <xsl:number level="single" count="chapter" format="1"/>. 
    <xsl:value-of select="title"/>
  </h2>
  <xsl:apply-templates select="section"/>
</xsl:template>

<!-- Number sections hierarchically -->
<xsl:template match="section">
  <p>
    <xsl:number level="multiple" count="section|chapter" format="1.1"/> 
    <xsl:value-of select="."/>
  </p>
</xsl:template>

Output

<h2>1. Introduction</h2>
<p>1.1 Overview</p>
<p>1.2 History</p>

<h2>2. Advanced</h2>
<p>2.1 Details</p>

Example 3: Roman numerals or letters

<xsl:number format="A"/>   <!-- A, B, C ... -->
<xsl:number format="a"/>   <!-- a, b, c ... -->
<xsl:number format="I"/>   <!-- I, II, III ... -->
<xsl:number format="i"/>   <!-- i, ii, iii ... -->

In short: <xsl:number> is the XSLT way of auto-generating sequence numbers, outlines, or hierarchical numbering for XML documents.