xsl:choose

Used to choose one of a number of alternative outputs.

Category: instruction
Content: ( xsl:when+ , xsl:otherwise? )
Permitted parent elements: any XSLT element whose content model is sequence-constructor; any literal result element
Element has no attributes

Saxon availability

Available in XSLT 1.0 and later versions. Available in all Saxon editions. Available for all platforms.

Notes on the Saxon implementation

Saxon-EE optimizes an xsl:choose instruction whose conditions are all of the form EXP = value where the left-hand expression is the same expression in each case, and the value is a literal (typically different in each case). The optimized form is similar to an XQuery switch expression: The expression EXP is only evaluated once, and a hash table is used to decide which branch to execute. Slight variants on this form of condition are also recognized, for example multiple such conditions connected by "or", or use of the operator "eq" in place of "=".

If the result of the xsl:choose instruction is required to be a particular type, the type checking is moved into each branch; this means that for any branch where the type can be verified statically, no dynamic check is needed. This also means that if there is any branch whose static type is incompatible with the required type, a compile-time error will be reported even if the branch is never executed.

Provided that syntax extensions are enabled, Saxon (from 10) allows the xsl:when and xsl:otherwise elements to return a value using a select attribute in place of a contained sequence constructor.

Details

The element typically contains a number of xsl:when elements, each with a separate test condition. The first xsl:when element whose condition matches the current element in the source document is expanded, the others are ignored. If none of the conditions is satisfied, the xsl:otherwise child element, if any, is expanded.

The test condition in the xsl:when element is a boolean expression. The full syntax of expressions is outlined in XPath syntax.

Examples

<xsl:choose> <xsl:when test="@cat='F'">Fiction</xsl:when> <xsl:when test="@cat='C'">Crime</xsl:when> <xsl:when test="@cat='R'">Reference</xsl:when> <xsl:otherwise>General</xsl:otherwise> </xsl:choose>

Links to W3C specifications

XSLT 2.0 Specification

XSLT 3.0 Specification

See also

xsl:when

xsl:otherwise

xsl:if