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 if 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

New in 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

New in 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

The new attributes then and else are available from Saxon 13 in XSLT 4.0; they are available in Saxon 10 to 12 provided that syntax extensions are enabled.

Details

The new then and else attributes are available in XSLT 4.0. If the then attribute is present, the xsl:if instruction must be empty (have no children). Either attribute can be used independently; there is no requirement for both to be present.

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 XSLT 4.0 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 3.0 Specification

XSLT 4.0 Specification

See also

xsl:choose