4.2.2.1. <xsl:choose> example
Here's a sample <xsl:choose> element that sets the background color of the table's rows. If the bgcolor attribute is coded on the <table-row> element, the value of that attribute is used as the color; otherwise, the sample uses the position() function and the mod operator to cycle the colors between papayawhip, mintcream, lavender, and whitesmoke.
<xsl:template match="table-row">
<tr>
<xsl:attribute name="bgcolor">
<xsl:choose>
<xsl:when test="@bgcolor">
<xsl:value-of select="@bgcolor"/>
</xsl:when>
<xsl:when test="position() mod 4 = 0">
<xsl:text>papayawhip</xsl:text>
</xsl:when>
<xsl:when test="position() mod 4 = 1">
<xsl:text>mintcream</xsl:text>
</xsl:when>
<xsl:when test="position() mod 4 = 2">
<xsl:text>lavender</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:text>whitesmoke</xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
<xsl:apply-templates select="*"/>
</tr>
</xsl:template>
In this sample, we use <xsl:choose> to generate the value of the bgcolor attribute of the <tr> element. Our first test is to see if the bgcolor attribute of the <table-row> element exists; if it does, we use that value for the background color and the <xsl:otherwise> and other <xsl:when> elements are ignored. (If the bgcolor attribute is coded, the XPath expression @bgcolor returns a node-set containing a single attribute node.)
The next three <xsl:when> elements check the position of the current <table-row> element. The use of the mod operator here is the most efficient way to cycle between the various options. Finally, we use an <xsl:otherwise> element to specify whitesmoke as the default case. If position() mod 4 = 3, the background color will be whitesmoke.
A couple of minor details: in this example, we could replace the <xsl:otherwise> element with <xsl:when test="position() mod 4 = 3">; that is logically equivalent to the example as coded previously. For obfuscation bonus points, we could code the second <xsl:when> element as <xsl:when test="not(position() mod 4)">. (Remember that the boolean negation of zero is true.)