Conditional Statements
If the expression in an <xsl:if>
, <xsl:when>
, or <xsl:otherwise>
element evaluates to true, the template body inside that conditional element is instantiated.
There are two kinds of conditional constructions: if, and choose/when/otherwise. For a simple statement that either does or does not perform an action, use if. To perform one action for one condition but a different action for a different condition, use choose/when/otherwise.
The test
attribute contains the expression to evaluate, and can be a comparison or an XPath expression. The expression evaluates to true if the expression returns any of the following:
- A non-empty node-set
- A non-zero number
- A non-empty result tree fragment
- A non-empty string
Example of <xsl:if>
<xsl:for-each select="//book"> <tr> <td> <xsl:value-of select="title"/> </td> <td> <xsl:attribute name="bgcolor">lightyellow</xsl:attribute> <xsl:if test="price > 10"> <xsl:attribute name="bgcolor">lightgreen</xsl:attribute> </xsl:if> <xsl:value-of select="price"/> </td> </tr> </xsl:for-each>
Example of <xsl:choose>
<xsl:for-each select="//book"> <div> <xsl:choose> <xsl:when test="self::*[genre = 'Romance']"> <xsl:attribute name="style">background-color: pink</xsl:attribute> </xsl:when> <xsl:when test="self::*[genre = 'Fantasy']"> <xsl:attribute name="style">background-color: lightblue</xsl:attribute> </xsl:when> <xsl:otherwise> <xsl:attribute name="style">background-color: lightgreen</xsl:attribute> </xsl:otherwise> </xsl:choose> <xsl:value-of select="title"/> </div> </xsl:for-each>
See Also
Defining Conditional Templates Using <xsl:if> and <xsl:choose> | xsl:choose Element | xsl:if Element