In this concluding article, expand your XSLT vocabulary by exploring conditional constructs, loops, variables, and numbering, together with examples and illustrations of how these programming capabilities can substantially simplify your XSLT experience.
The example you just saw used an ordered list to display the items in correct numeric order. Now, while this is fine and dandy so long as you're only outputting HTML, what happens if you suddenly need to output the same data as ASCII text, which doesn't come with a convenient auto-numbering feature?
Well, have no fear - XSLT comes with its own built-in numbering system, accessed via the <xsl:number> instruction. This construct comes in very handy when you need to print a series of sequential numbers, or print numbers in a style different from the standard decimal system.
Let's take a look at how it works, by using the following XML document as source data:
1Be Cool
2Mystic River
3Hit List
4Silent Joe
5The Travel Detective
In this case, the position of each node in the collection is used as the number.
In case the number format doesn't work for you, you can alter it with the "format" attribute - try the format "I" for Roman numerals, or "a" for alphabetic numbering. The rule
I. Be Cool
II. Mystic River
III. Hit List
IV. Silent Joe
V. The Travel Detective
In addition to this simple numbering mechanism, XSLT also allows you to count and display specific types of nodes within the document. For example, if I needed to display a number next to each of the steps in the process below,
<?xml version="1.0"?>
<recipe>
<ingredients>
<item>Boneless
chicken breasts</item>
<item>Chopped onions</item>
<item>Ginger</item>
</ingredients>
<process>
<step>Cut
chicken into cubes, wash and apply lime juice and salt</step>
<step>Add
ginger, garlic, chili, coriander and lime juice in a separate
bowl</step>
<step>Mix
well, and add chicken to marinate for 3-4 hours</step>
<step>Place chicken
pieces on skewers and barbeque</step>
<step>Remove, apply butter, and
barbeque again until meat is tender</step>
<step>Garnish with lemon and
chopped onions</step>
</process>
</recipe>
Here, the second template rule specifies that only "step" elements are to be
counted and numbered. Note, however, that this numbering mechanism only works on nodes at the same level in the node tree - if you'd like to include nodes at other levels, there's an additional "level" attribute you need to use.