How Does XSLT xsl:number Level Attribute Work?

The level attribute of the <xsl:number> element dictates the scope and structural depth used to calculate sequential numbers in hierarchical XML documents. By choosing between single, multiple, or any, XSLT developers can control whether numbering resets at parent boundaries, generates multi-tiered outline structures (such as 1.2.3), or counts nodes sequentially across the entire document tree.

Understanding the Three Values of the Level Attribute

The <xsl:number> instruction relies on the level attribute to determine which ancestor and preceding sibling nodes are factored into the sequence calculation.

1. level="single" (Default)

When set to single, XSLT targets only the nearest ancestor or the current node that matches the criteria in the count attribute, counting it among its preceding siblings.

2. level="multiple"

The multiple setting is designed specifically for hierarchical, multi-tiered document structures like outlines, legal documents, and table of contents generation.

3. level="any"

The any setting ignores tree hierarchy and ancestor boundaries entirely.

Comparison of Level Attributes

Level Attribute Scope Output Format Example Counter Reset Behavior
single Nearest matching ancestor 3 Resets per parent container
multiple All matching ancestors 1.4.2 Resets per ancestor branch
any Entire document tree 12 Never resets (global count)

Practical Implementation in Hierarchical Documents

To generate multi-level outline numbering, level="multiple" is paired with the count and format attributes:

<xsl:number 
    level="multiple" 
    count="chapter | section | subsection" 
    format="1.1.1 " />

When evaluating a subsection element nested inside the third section of the second chapter, XSLT evaluates each component of the count pattern:

  1. Position of chapter among sibling chapters: 2
  2. Position of section among sibling sections: 3
  3. Position of subsection among sibling subsections: 1

The resulting output renders as 2.3.1 , dynamically constructing the complete multi-level identifier based on the node's position within the document hierarchy.