XSLT Function: xsl:if

The XSLT <xsl:if> element provides a simple conditional test to use against the contents of an XML file.

<xsl:if> 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:if> element does not support else or else-if constructs; if something more is required then look into using the <xsl:choose> element instead.


<xsl:if select="expression">
<!-- Do something when evaluating to true. -->

where expression is either a Boolean  XPATH expression or XSLT variable reference. The contents of the <xsl:if> 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).


For our examples we are using the fictional library as an input XML. Any XSL transform examples we define uses this XML as an input.

<?xml version="1.0" encoding="UTF-8"?>
<category name="dogs">
<name>All about dogs</name>
<category name="cats">
<name>All about cats</name>

How to process conditional if-statements

The following XSL transform shows test for a condition against the XML document, and if true, process specific instructions. The purpose of the transform is to determine if there is a category with a name starting with the letter ‘d’, and if found, write this name to the output. If a category with a name starting with ‘d’ is not found, then nothing is written to the output.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="category">
<xsl:if test="starts-with(@name, 'd')">
FOUND: <xsl:value-of select="./@name"/>

The results of the above XSL transform is as follows:

FOUND: dogs

Posted in XSLT and tagged .

Leave a Reply