Using if Instead of <xsl:choose>
Although the XSLT elements <xsl:if>, <xsl:choose>, <xsl:when>, and <xsl:otherwise>
provide the same function as the if-then-else functions of most
programming languages, they’re much more verbose. We can use the XPath
2.0 and XQuery 1.0 if operator to
simplify things.
Our XSLT 1.0 stylesheet uses <xsl:choose> in two places: to choose
the background color of table rows, and to change the decimal format
for currency amounts in the first row of each purchase order. Here’s
the first <xsl:choose>:
<tr>
<xsl:attribute name="style">
<xsl:text>background: </xsl:text>
<xsl:choose>
<xsl:when test="position() mod 2">
<xsl:text>#CCCCFF</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:text>#66FF66</xsl:text>
</xsl:otherwise>
</xsl:choose>
<xsl:text>;</xsl:text>
</xsl:attribute>We create an attribute named style. If this is an odd-numbered row
(position() mod 2 is 1, which evaluates to true), we set the background color to
#CCCCFF; otherwise, we set it to
#66FF66. In our XSLT 2.0
stylesheet, we can replace those elements with this attribute value
template:
<tr style="{if (position() mod 2)
then 'background: #CCCCFF;'
else 'background: #66FF66;'}">The other place we use <xsl:choose> is to choose a decimal
format. Here’s how we do it in XSLT 2.0:
<xsl:value-of
select="if (position() = 1)
then format-number(price * qty, '$#,###.00')
else format-number(price * qty, '#,###.00')"/>In both cases, we’ve replaced several elements with a single
if statement inside an attribute. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access