XSLT » Elements » xsl:if


The xsl:if element evaluates an expression which returns a Boolean result to determine if a template should be instantiated. The evaluation is a simple True or False test on a defined condition or a set of conditions. If the test returns True, the template is applied and the results are displayed in the output. If False, the template is not applied (i.e., the contents between the opening and closing xsl:if are skipped over).

The actions of the xsl:if element are analogous to the if statement found in many other computer languages, such as in C and VBScript. However, there is no else statement. Therefore, if you need to choose from two or more possible courses of action, you may prefer to use the xsl:choose element.
One possible use of this element is to test for errors. The xsl:message element can be used to display error messages.
This is not a self-closing element. The separate closing element is mandatory.


<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html" />
<xsl:template match="/">
The DevGuru Staff Members are
<xsl:for-each select="devguru_staff/programmer">
<xsl:value-of select="name" />
<xsl:if test="position()!=last()">
<xsl:text>, </xsl:text>
<xsl:if test="position()=last()-1">
<xsl:text> and </xsl:text>
<xsl:if test="position()=last()">
The DevGuru Staff Members are Bugs Bunny, Daisy Duck, Minnie Mouse, Pluto, Porky Pig, and Road Runner!

This is the code for xslt_example_if.xsl.
We use the DevGuru Staff List XML file for our example with the following header:
<?xml-stylesheet type="text/xsl" href="xslt_example_if.xsl"?>

Language(s): XSLT

See Also: