SoFunction
Updated on 2025-04-08

XSL brief tutorial (7) XSL control statements

Original: Jan Egil Refsnes Translation: Ajie

7. XSL control statements


1. Conditional statement if...then

XSL also has conditional statements (hehe~~so amazing, like a programming language). The specific syntax is to add an xsl:if element, similar to this

<xsl:if match=".[ARTIST='Bob Dylan']">

... some output ...

</xsl:if>


The above example is rewritten as:

<?xml version='1.0'?>

<xsl:stylesheet xmlns:xsl="http:///TR/WD-xsl">

<xsl:template match="/">

<html>

<body>

<table border="2" bgcolor="yellow">

<tr>

<th>Title</th>

<th>Artist</th>

</tr>

<xsl:for-each select="CATALOG/CD">

<xsl:if match=".[ARTIST='Bob Dylan']">

<tr>

<td><xsl:value-of select="TITLE"/></td>

<td><xsl:value-of select="ARTIST"/></td>

</tr>

</xsl:if>

</xsl:for-each>

</table>

</body>

</html>

</xsl:template>

</xsl:stylesheet>


2. XSL's Choose

The purpose of choice is to show multiple conditions and give different display results. The specific syntax is to add a set of xsl:choose,xsl:when,xsl:otherwise elements:


<xsl:choose>

<xsl:when match=".[ARTIST='Bob Dylan']">

... some code ...

</xsl:when>

<xsl:otherwise>

... some code ....

</xsl:otherwise>

</xsl:choose>


The above example is rewritten as:

<?xml version='1.0'?>

<xsl:stylesheet xmlns:xsl="http:///TR/WD-xsl">

<xsl:template match="/">

<html>

<body>

<table border="2" bgcolor="yellow">

<tr>

<th>Title</th>

<th>Artist</th>

</tr>

<xsl:for-each select="CATALOG/CD">

<tr>

<td><xsl:value-of select="TITLE"/></td>

<xsl:choose>

<xsl:when match=".[ARTIST='Bob Dylan']">

<td bgcolor="#ff0000"><xsl:value-of select="ARTIST"/></td>

</xsl:when>

<xsl:otherwise>

<td><xsl:value-of select="ARTIST"/></td>

</xsl:otherwise>

</xsl:choose>

</tr>

</xsl:for-each>

</table>

</body>

</html>

</xsl:template>

</xsl:stylesheet>