xsl:switch

New in XSLT 4.0. Used to choose one of a number of alternative outputs, based on the value of a supplied expression.

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

Attributes

select

expression

Computes an atomic item that is compared with the values in the test attributes of the xsl:when children.

Saxon availability

Available in XSLT 4.0. Requires Saxon-PE or Saxon-EE. Implemented since Saxon 11. Available for all platforms.

Notes on the Saxon implementation

The xsl:switch instruction is available from Saxon 13 in XSLT 4.0; it is available in Saxon 11 and 12 provided that syntax extensions are enabled.

Details

The select attribute contains an expression which must deliver a single atomic item (it is atomized if necessary). This value is compared with the values of the test conditions in each of the contained xsl:when elements in turn until the first match is found. If a match is found, that xsl:when element is evaluated; if no match is found, the xsl:otherwise element is evaluated; if there is no xsl:otherwise element, the xsl:switch instruction returns an empty sequence.

Unlike xsl:choose, the test condition in the xsl:when element is an expression that can evaluate to any sequence of atomic items. The comparison is done using the "=" operator, so the test succeeds if any of the values matches.

Examples

Example 1

<xsl:switch select="@cat"> <xsl:when test="'F'">Fiction</xsl:when> <xsl:when test="'C'">Crime</xsl:when> <xsl:when test="'R', 'L'" select="my:f(@cat)"/> <xsl:otherwise>General</xsl:otherwise> </xsl:switch>

Example 2

The new syntax can be particularly useful when computing the return value of a function, replacing xsl:sequence:

<xsl:function name="f:days-in-month" as="xs:integer?"> <xsl:param name="month-number" as="xs:integer"/> <xsl:param name="leap-year" as="xs:boolean"/> <xsl:switch select="$month-number"> <xsl:when test="1, 3, 5, 7, 8, 10, 12" select="31"/> <xsl:when test="4, 6, 9, 11" select="30"/> <xsl:when test="2"> <xsl:if test="$leap-year" then="29" else="28"/> </xsl:when> </xsl:switch> </xsl:function>

Links to W3C specifications

XSLT 4.0 Specification

See also

xsl:when

xsl:otherwise