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.

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.

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