Working with Numbered Lists
The position() function
The position() function returns the position of the context node in a selected set of nodes. The following XML and XSLT documents illustrate how position() works.
This can be corrected by selecting a specific node-set with the xsl:apply-templates tag, but that can cause other problems.
The <xsl:number/> tag provides another mechanism for numbering elements. It counts nodes that match a specified XPath. It works as follows.
First, xsl:number takes a count attribute, which takes an XPath indicating which elements to count. When not specified, the default of count is the name of the current element. When specified, the processor first looks at the current node and then looks up the tree at the current node's ancestors until it finds an element that matches the XPath specified in count. It stops as soon as it finds a match.
Second, xsl:number takes a level attribute, which determines how many levels of the XML document should be examined for nodes that match the pattern specified in the count attribute. Possible values are single, multiple and any. We'll look at examples of each of these.
level = "single"
When level="single" (the default), a count is done of the node matched in the count attribute plus all preceding siblings that also match the XPath specified in count.
When level="any", a count is done of the node matched in the count attribute plus all preceding elements that also match the XPath specified in count.
To illustrate how any works, we'll first take a look at another example using level="single".
When level="multiple", multiple counts are done at different levels. To determine the results, the processor goes through the following steps.
- It creates a list of all the ancestors of the current node and the current node itself.
- It throws out any nodes in the list that do not match the XPath specified in the count attribute.
- It maps each node in the list to a number, which is calculated by counting the node's preceding siblings that match the XPath specified in the count attribute and adding one (for the node itself).
The from attribute takes a regular expression specifying where counting should start.
In the last example, you may have noticed that the levels are all represented with Arabic numbers. The formatting can be changed with the format attribute, which takes a format token, which is a delimited list of characters. The same delimiter used in the format token is used in the output.
In earlier examples, we placed a period and a space after the number by putting <xsl:text>. </xsl:text> after xsl:number. In this example, we accomplished the same thing by placing a period and a space at the end of the format token.