Conditional Processing
There are two instructions in XSL that allow you to conditionally process an element according to certain test conditions: xsl:if and xsl:choose.
The xsl:if instruction provides simple if (a), then (b) conditionality. The xsl:choose instruction enables you to select one choice when there are several possibilities.
The xsl:if element has a single test attribute, which specifies a test pattern. The content is a template. If the pattern selects a non-empty list of elements, the content is instantiated; otherwise nothing is created.
In the following example, the names in a group of names are formatted as a comma-separated list:
<xsl:template match="namelist/name"> <xsl:apply-templates/> <xsl:if test=".[not(last-of-type())]">, </xsl:if> </xsl:template>
The xsl:choose element selects one from among a number of possible alternatives. It consists of a series of xsl:when elements followed by an optional xsl:otherwise element.
Each xsl:when element has a single test attribute, which specifies a test pattern. The result of the test is true if the pattern selects a non-empty list of elements.
The content of the xsl:when and xsl:otherwise elements is a template. When an xsl:choose element is processed, each of the xsl:when elements is tested in turn. The content of the first, and only the first xsl:when element whose test is true is used. If no xsl:when element is true, the content of the xsl:otherwise element is used. If no xsl:when element is true, and no xsl:otherwise element is present, nothing is created. You should therefore make a habit of always specifying an xsl:otherwise element.
The example XSL style sheet shown in Listing 20.12 enumerates items in an ordered list using Arabic numerals, letters, or roman numerals depending on the depth to which the ordered lists are nested.
Listing 20.12 Conditional Processing in an XSL File
1: <xsl:template match="list/item"> 2: <fo:list-item indent-start='12pt'> 3: <fo:list-item-label> 4: <xsl:choose> 5: 6: <xsl:when test='ancestor(list/list)'> 7: <xsl:number format="i"/> 8: </xsl:when> 9: 10: <xsl:when test='ancestor(list)'> 11: <xsl:number format="a"/> 12: </xsl:when> 13: 14: <xsl:otherwise> 15: <xsl:number format="1"/> 16: </xsl:otherwise> 17: 18: </xsl:choose> 19: 20: <xsl:text>. </xsl:text> 21: </fo:list-item-label> 22: 23: <fo:list-item-body> 24: <xsl:apply-templates/> 25: </fo:list-item-body> 26: 27: </fo:list-item> 28: 29: </xsl:template>