<xsl:choose> Element
Tests multiple conditions in conjunction with the <xsl:otherwise> and <xsl:when> elements.
<xsl:choose> </xsl:choose>
Element Information
| Number of occurrences | Unlimited |
| Parent elements | xsl:attribute, xsl:comment, xsl:copy, xsl:element, xsl:fallback, xsl:for-each, xsl:if, xsl:message, xsl:otherwise, xsl:param, xsl:processing-instruction, xsl:template, xsl:variable, xsl:when, xsl:with-param, output elements |
| Child elements | xsl:otherwise, xsl:when |
Remarks
The <xsl:when> children of the <xsl:choose> element are tested, in order from top to bottom, until a test attribute on one of these elements accurately describes conditions in the source data, or until an <xsl:otherwise> element is reached. Once an <xsl:when> or <xsl:otherwise> element is chosen, the <xsl:choose> block is exited. No explicit break or exit statement is required.
For simple conditional testing, use the <xsl:if> element.
Example
The following example shows a template for <order> elements, and inserts a size indicator before the contents of each <order>. This size indicator is based on the value of the <total> element within each <order> element. If the total is less than 10, the text "(small)" is added. If the total is less than 20, the text "(medium)" is added. If the total is 20 or more, the text "(large)" is added.
Note To test this example, you need to use a script. For more information, see Initiate XSLT in a Script.
XML File (order.xml)
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="refchoose.xsl" ?>
<orders>
<order>
<lineitem/>
<lineitem/>
<total>9</total>
</order>
<order>
<lineitem/>
<lineitem/>
<total>19</total>
</order>
<order>
<lineitem/>
<lineitem/>
<total>29</total>
</order>
</orders>
XSLT File (refchoose.xsl)
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:template match="order">
<xsl:choose>
<xsl:when test="total < 10">
(small)
</xsl:when>
<xsl:when test="total < 20">
(medium)
</xsl:when>
<xsl:otherwise>
(large)
</xsl:otherwise>
</xsl:choose>
<xsl:apply-templates />
<BR/>
</xsl:template>
</xsl:stylesheet>
Output
(small) 9
(medium) 19
(large) 29
See Also
Defining Conditional Templates Using <xsl:if> and <xsl:choose>
