- Expression can be any valid predicate.
-
<xsl:template match="cd">
<xsl:if test="price > 10">
...
</xsl:if>
</xsl:template>
<xsl:template match="cd">
<xsl:if test="country = 'UK'">
...
</xsl:if>
</xsl:template>
- Typically the same test could be placed with the match or
select attribute of the enclosing operator so in single-case
situations it's probably clearer to put the test in the
match or select attribute and not use the if operator.
- if's are best used when you want to do the same formatting
for most of the tag but want to tweak the formatting in the
middle. For example, for a cd I might want to always print
the title and artist, but in addition I might want to print
an asterisk next to the title if the cd's price is
greater than 10. Here's how I might do it with an if
element:
<xsl:for-each select="cd">
<tr>
<td><xsl:value-of select="title"/>
<xsl:if test="price > 10"><sup>*</sup></xsl:if></td>
<td><ol>
<xsl:value-of select="artist" />
</xsl:for-each>
- if components must obey xml nesting requirements,
which can prevent you from accomplishing seemingly simple
tasks. For example, suppose we want to boldface titles that
are associated with cd's whose price is $10. We might want
to put an if clause before and after the title that adds
a boldface element and a matching boldface terminator. For
example:
<td><xsl:if test="price > 10"><b></xsl:if>
<xsl:value-of select="title" />
<xsl:if test="price > 10"></b></xsl:if>
</td>
This code represents an improperly nested piece of xml code
because the <b> was not terminated before the
<xsl:if> element. So even though the code would
produce a properly nested html document if it were
executed, the code will never get executed. To get the
title to be properly bold-faced, I would need to use a
choose statement:
|
The choose operator is discussed next.