XML technologies / XSLT / Introduction to XSLT 2.0 / XSLT and XPath – round two / Conditions with XSLT and XPath / Decisions with XSLT: xsl:if
(Excerpt from “XSLT 2.0 & XPath 2.0” by Frank Bongers, chapter 2.)
The instruction xsl:if is essentially a practical switch that enables or disables parts of a template block. Only the IF branch of a typical condition is present. For xsl:if there is only an if decision, no else branch, so no corresponding xsl:else.
If evaluating the value of the test attribute yields true, the contents of the xsl:if container are executed; otherwise they are skipped entirely.
<xsl:template match="buch">
<p><xsl:apply-templates/><xsl:if test="@isbn"><br/>(ISBN: <xsl:value-of select="@isbn"/>)</xsl:if></p>
</xsl:template>
Code example: kap02/2.02.1/buchhande1-if1.xsl (excerpt).
A template processing <buch> elements outputs the processed book’s ISBN in parentheses if that information exists. The test is: “isbn attribute present? yes/no”. The attribute’s value does not matter. However, the value may be empty, as it is for two books. You should account for this by extending the condition:
<xsl:if test="@isbn != ' '">
This test is true if the attribute’s value is not the empty string, and false both when the attribute exists but is empty and when it is absent.
<xsl:template match="buch">
<p><xsl:if test="@ersch-jahr > 2003"><i>Neu erschienen:</i><br /></xsl:if><xsl:apply-templates/></p>
</xsl:template>
Code example: kap02/2.02.1/buchhande1-if1b.xsl (excerpt).
Here a corresponding note is inserted for books published after 2003. As with predicates, the operator symbol > must also be written as the entity reference >. Of course, you can also use operators = (equal), < (less than) or != (not equal) here.
Here is an example inserting a special-offer note and a separator line for books priced below €15. The price’s currency is ignored:
<xsl:template match="buch">
<p><xsl:if test="preis < 15"><b>Sonderangebot:</b><br/></xsl:if><xsl:apply-templates/></p>
<xsl:if test="preis < 15">
<hr/>
</xsl:if>
</xsl:template>
Code example: kap02/2.02.1/buchhande1-if2.xsl (excerpt).
This can also exclude particular items in an input sequence from processing when prior predicate filtering is impossible or inappropriate.
Copyright © Galileo Press, Bonn 2008
You may print the online version for your private use.
Otherwise, this chapter from “XSLT 2.0 & XPath 2.0 ― Das umfassende Handbuch” is subject to the same conditions as the bound edition. The work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
Galileo Press, Rheinwerkallee 4, 53227 Bonn