How Does xsl:number Work in XSLT?

The <xsl:number> element in XSLT is a dedicated instruction used to compute sequential counts, hierarchical numbering, and custom numeric or alphabetic formatting directly from the source XML tree. Rather than requiring developers to manage procedural loops or index counters, <xsl:number> evaluates a node’s position within the document structure and automatically generates ordered values such as simple lists, multi-level chapter outlines, or Roman-numeral sequences.

Core Purpose and Functionality

In declarative stylesheet processing, maintaining sequential counters can be challenging because variables in XSLT are immutable. The <xsl:number> element solves this by inspecting the position of the current node relative to its siblings, ancestors, or specified pattern matches.

The primary use cases include:

Controlling Numbering Scope with the Level Attribute

The level attribute determines how XSLT scans the XML hierarchy to determine the sequence number. It supports three distinct modes:

  1. Single (level="single"): This is the default mode. It counts the target node among its preceding siblings with the same name or matching pattern, resulting in flat, single-digit sequences.
  2. Multiple (level="multiple"): This mode traverses up the ancestor tree, generating a compound sequence representing each hierarchical level. For example, a <subsection> inside a <section> inside a <chapter> can automatically produce identifiers like 3.2.1.
  3. Any (level="any"): This mode counts all matching nodes that appear prior to the current node across the entire document tree, regardless of depth or parent containers.

Fine-Tuning with Count and From Attributes

To refine which nodes are included or where the counter resets, <xsl:number> provides pattern-matching attributes:

Formatting Options

The format attribute specifies how the calculated integer is rendered into the final output. Common formats include:

Difference Between xsl:number and position()

While the XPath position() function returns the index of a node within the currently processed node-set, <xsl:number> determines position based on the source document structure itself. This makes <xsl:number> especially valuable when processing filtered selections, complex hierarchies, or when specialized visual formatting like Roman numerals or chapter-level prefixes is required.