In this concluding article, expand your XSLT vocabulary by exploring conditional constructs, loops, variables, and numbering, together with examples and illustrations of how these programming capabilities can substantially simplify your XSLT experience.
In case you find the "if" test a little too primitive for your needs, XSLT also offers the instruction. This is a lot like the "switch/case" statements you may be familiar with from PHP or JSP, and it looks like this:
<xsl:choose>
<xsl:when test="first_condition_is_true">
do this!
</xsl:when>
<xsl:when
test="second_condition_is_true ">
do this!
</xsl:when>
<xsl:when test="third_condition_is_true ">
do this!
</xsl:when>
...
and so on ...
<xsl:otherwise>
all tests failed, do this!
</xsl:otherwise>
</xsl:choose>
An example might help to make this clearer. Take a look at this XML document,
which contains original and current prices for some fictitious stocks.
Now, let's suppose I wanted to find out which of these stocks had risen in value,
which had decreased, and which had remained static. I could use an XSLT stylesheet to calculate the change in value and display an appropriate message - maybe with a colour code - next to each stock in the list.
<xsl:template match="/portfolio">
<html>
<head>
<basefont face="Arial"
size="2"/>
</head>
<body>
<h3>Portfolio At A Glance:</h3>
<ul>
<xsl:apply-templates
/>
</ul>
</body>
</html>
</xsl:template>
<xsl:template match="stock">
<xsl:choose>
<!--
if price has gone up -->
<xsl:when test="(cprice - oprice) > 0">
<li><font
color="blue"><xsl:value-of select="symbol" /></font> (up by
<xsl:value-of
select="round(((cprice - oprice) * 100 div oprice))" />%)</li>
</xsl:when>
<!--
if price has gone down -->
<xsl:when test="(cprice - oprice) < 0">
<li><font
color="red"><xsl:value-of select="symbol" /></font> (down by
<xsl:value-of
select="round(((cprice - oprice) * 100 div oprice) * -1)"
/>%)</li>
</xsl:when>
<!--
no change -->
<xsl:otherwise>
<li><xsl:value-of select="symbol" />
(no change)</li>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
Here's what it looks like:
As you can see, the <xsl:choose> conditional statement has been used to find out whether a stock has increased or decreased in value, with a template generated appropriately. The calculations you see within the template rule are all used to display the change in value in percentage terms, and again illustrate how XSLT can be used to combine disparate bits of information from the source tree to create a new and different view in the result tree.