XSLT allows you to perform basic conditional tests within a template rule. The simplest form of conditional instruction is the
instruction, which looks something like this
<xsl:if test="condition">
do this!
</xsl:if>
The "condition" here is a conditional expression, which evaluates to either true
or false. If the statement evaluates to true, the template is used; if not, it is ignored by the processor.
Consider the following XML document:
<?xml version="1.0"?>
<inventory>
<item>
<name>Brand Alpha</name>
<rating>7</rating>
</item>
<item>
<name>Brand
Beta</name>
<rating>9</rating>
</item>
<item>
<name>Brand
Gamma</name>
<rating>2</rating>
</item>
</inventory>
Here's a stylesheet to display these items as a list. Note how a conditional
test has been used to display an asterisk next to items with a high rating.
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template
match="/inventory">
<html>
<head>
<basefont face="Arial" size="2"/>
</head>
<body>
<ul>
<xsl:apply-templates
/>
</ul>
</body>
</html>
</xsl:template>
<xsl:template match="item">
<li><xsl:value-of
select="name" /></li>
<xsl:if test="rating > 5">
*
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Here's what it looks like:

Here are a couple more examples of how this text can be used. The first template rule places the word "and" before printing the last item in the selected node collection, while the second displays a warning based on the value of a node.
<xsl:template match="person">
<xsl:if test="position() = last()">
and
</xsl:if>
<xsl:value-of
select="." />
</xsl:template>
<xsl:template match="/">
<xsl:if test="//temp
> 500">
<font size="+2" color="red">Warning! Temperature above acceptable
limits!</font>
</xsl:if>
</xsl:template>
Next: The Number Game >>
More XML Articles
More By icarus, (c) Melonfire