<xsl:if>

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.

Syntax


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

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.

Attributes

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

Examples

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"?>
<library>
<category name="dogs">
<book>
<name>All about dogs</name>
<author>Someone</author>
<isin>true</isin>
<daysuntilreturn>0</daysuntilreturn>
</book>
</category>
<category name="cats">
<book>
<name>All about cats</name>
<author>Someone</author>
<isin>false</isin>
<daysuntilreturn>3</daysuntilreturn>
</book>
</category>
</library>

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"/>
</xsl:if>
</xsl:template>
</xsl:stylesheet>

The results of the above XSL transform is as follows:

FOUND: dogs

Posted in XSLT and tagged .

Leave a Reply