xsl:if

Used for conditional processing. It takes a mandatory test attribute, whose value is a boolean expression. The contents of the xsl:if element are expanded only of the expression is true.

Category: instruction
Content: sequence-constructor
Permitted parent elements: any XSLT element whose content model is sequence-constructor; any literal result element

Attributes

test

expression

The boolean expression to be tested. The full syntax of boolean expressions is outlined in XPath syntax.

then?

expression

Proposed extension for XSLT 4.0; defines the value to be returned if the test condition is true, as an alternative to evaluating the sequence constructor. If the then attribute is present, the xsl:if element must be empty.

else?

expression

Proposed extension for XSLT 4.0; defines the value to be returned if the test condition is false, as an alternative to returning an empty sequence.

Saxon availability

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

Notes on the Saxon implementation

Provided that syntax extensions are enabled, Saxon (from 10) allows the xsl:if instruction to have a then and/or else attribute. The then attribute defines an expression to be evaluated when the test condition is true; if it is present, then the xsl:if instruction must be empty. The else attribute defines an expression to be evaluated when the test condition is false; it defaults to the empty sequence.

Details

The new then and else attributes are available only if XSLT syntax extensions are enabled.

Note that forwards-compatibility mode in previous versions of XSLT does not handle these extensions particularly well. If an XSLT 3.0 processor encounters an xsl:if instruction with a then or else attribute, and the instruction has an effective version of 4.0, the then and else attributes will simply be ignored, which will generally give incorrect results.

Examples

Example 1

To include a hyperlink in the output only if the current element has a preface attribute:

<xsl:if test="@preface"> <a href="preface.html">Preface</a> </xsl:if>

Example 2

A function that performs head-tail recursion, using Saxon's extended syntax:

<xsl:function name="f:product" as="xs:double"> <xsl:param name="input" as="xs:double*"/> <xsl:if test="empty($input)" then="1" else="head($input) * f:product(tail($input))"/> </xsl:function>

Links to W3C specifications

XSLT 2.0 Specification

XSLT 3.0 Specification

See also

xsl:choose