XSLT Function: xsl:when

The XSLT <xsl:when> element provides a conditional test to use against the contents of an XML file within the scope a larger <xsl:choose> conditional evaluation.

<xsl:when> supports one attribute – test – which must return a Boolean value (true or false) through the application of a XPATH expression, or evaluation of a variable.

The <xsl:when> element cannot be used on its own; it must always be used together with the <xsl:choose> element. When used inside an <xsl:choose> then only the first <xsl:when> whose test evaluates to true will be processed.

If your intention is to evaluate a simple Boolean expression (and not a sequence of alternatives) and nothing else, then look into using the <xsl:if> element instead.


<xsl:when test="expression_1">
<!-- evaluated when expression_1 is true. -->
<xsl:when test="expression_2">
<!-- evaluated when expression_2 is true. -->
<!-- ... -->
<xsl:when test="expression_n">
<!-- evaluated when expression_n is true. -->
<!-- evaluated when none of the preceding expressions are true.-->

<xsl:choose> contains one or more nested <xsl:when> elements and one optional <xsl:otherwise> element. Only the contents one <xsl:when> element is evaluated when its corresponding expression returns true; otherwise the <xsl:otherwise> content is evaluated if defined.


   2: <xsl:when select="expression">

   3:     <!-- Do something when evaluating to true. -->

   4: </xsl:when>



where expression is either a Boolean  XPATH expression or XSLT variable reference. The contents of the <xsl:when> element is evaluated if the expression returns a true value.


testMANDATORYan XPATH expression or variable reference which returns / represents a Boolean value (true or false).


The <xsl:when> element must be used inside a <xsl:choose> element. Refer to the examples presented under <xsl:choose> for a better overview on how to use this function in an XSLT transform.

Posted in XSLT and tagged .

Leave a Reply