XML technologies / XSLT / XSLT Cookbook / XPath / Simplifying conditional code with if expressions
(Excerpt from "XSLT Kochbuch" by Sal Mangano)
Problem
Your complex XSLT code is too verbose because of XML overhead when expressing simple if-then-else conditions.
Solution
XPath 1.0
Some tricks in XPath 1.0 avoid the verbose XSLT construct xsl:choose in simple situations. They rely on mathematical contexts converting false to 0 and true to 1.
Minimum, maximum and absolute values can therefore be calculated directly in XPath 1.0. These examples assume $x and $y contain integers.
(: min :)
($x <= $y) * $x + ($y < $x) * $y
(: max :)
($x >= $y) * $x + ($y > $x) * $y
(: abs :)
(1 - 2 * ($x < 0)) * $x
XPath 2.0
The simple cases in the XPath 1.0 section (min, max, abs) now have built-in XPath functions. For other simple conditions, use the new conditional expression if.
(: Der Wert eines fehlenden Attributs wird standardmäßig auf 10 gesetzt. :)
if (@x) then @x else 10
(: Der Wert eines fehlenden Elements wird standardmäßig auf 'unauthorized' gesetzt. :)
if (password) then password else 'unauthorized'
(: Schutz vor der Division durch null. :)
if ($d ne 0) then $x div $d else 0
(: Ein para-Element, wenn es wenigstens ein Zeichen enthält, das kein Leerraum ist; ansonsten ein einzelnes Leerzeichen. :)
if (normalize-space(para)) then string(para) else ' '
Discussion
Longtime XSLT 1.0 programmers may wince whenever they must add conditional code to a template. I do, and often try hard to exploit XSLT pattern matching to minimize conditions. The code is not necessarily harder or less efficient, merely painfully verbose. A simple xsl:if is tolerable, but if-then-else logic requires the bulkier xsl:choose. Ugh!
In XSLT 2.0, an alternative exists, actually provided by XPath 2.0 rather than XSLT 2.0. At first, adding what procedural programmers call control-flow statements might seem to corrupt XPath. Once you fully explore XPath 2.0, however, you will see that these extensions improve both XPath and XSLT. The conditional expression does not reject xsl:if; it reduces the need to use it in its most awkward cases. Compare the following code:
<!-- XSLT 1.0 -->
<xsl:variable name="size">
<xsl:choose>
<xsl:when test="$x > 3">groß</xsl:when>
<xsl:otherwise>klein</xsl:when>
</xsl:choose>
</xsl:variable>
<!-- XSLT 2.0 -->
<xsl:variable name="size" select="if ($x gt 3) then 'groß' else 'klein' "/>Most readers will probably prefer the second XPath 2.0 solution to the preceding XSLT 1.0 solution.
A crucial fact is that else is not optional. C programmers can compare this construct to a ? b : c. An empty sequence () is often used if no other meaningful value exists for the expression’s else part.
Conditional expressions provide defaults when no schema supplies them.
(: Angeben einer Vorgabe für den Wert eines optionalen Attributs :)
if (@optional) then @optional else 'irgendeine-Vorgabe'
(: Angeben einer Vorgabe für den Wert eines optionalen Elements :)
if (optional) then optional else 'irgendeine-Vorgabe'
They also handle undefined or unwanted results. Here, an application-specific reason makes 0 preferable to number('Infinity') as the result.
if ($divisor ne 0) then $dividend div $divisor else 0
More complex conditions are also possible. This code produces a bulleted list:
if (size eq 'XXL') then 50
else if (size eq 'XL') then 45else if (size eq 'L') then 40
else if (size eq 'M') then 34
else if (size eq 'S') then 32
else if (size eq 'XS') then 29
else -1
Here, a sequence-based solution is probably cleaner, especially if literal sequences become variables initialized from an external XML file.
(50,45,40,34,32,29,-1)[(index-of((('XXL', 'XL', 'L', 'M', 'S', 'XS')), size), 7)[1]]
We assume the context has exactly one child size; otherwise, the expression is invalid, although you could write size[1] instead. We also rely on index-of returning an empty sequence when the desired item, concatenated with 7 to handle the else case, is absent.
Copyright © 2006 O'Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "XSLT Kochbuch" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.
O'Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de