Skip to main content

XSLT <xsl:otherwise>

XSLT <xsl:otherwise>

The <xsl:otherwise> element specifies a default action for the <xsl:choose> element. This action will take place when none of the <xsl:when> conditions apply.

Syntax

<xsl:otherwise>
<!-- Content:template -->
</xsl:otherwise>

Attributes

The <xsl:otherwise> element has no attributes.

Example

Let's see some examples:

Example 1

Consider the XML document about a bookstore shown below:

books.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="books.xsl"?>

<bookstore>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Tips</title>
<author>Tom Nolan</author>
<year>2022</year>
<price>39.99</price>
</book>
<book category="web">
<title lang="en">Learn XML</title>
<author>Tutorial Reference</author>
<year>2022</year>
<price>9.99</price>
</book>
</bookstore>

The code below will add a red background-color to the author column when the price of the book is higher than 15, otherwise it will just print the name of the author:

books.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
<body>
<h2>The Bookstore</h2>
<table border="1">
<tr bgcolor="#6565d5">
<th>Title</th>
<th>Author</th>
</tr>
<xsl:for-each select="bookstore/book">
<tr>
<td><xsl:value-of select="title"/></td>
<xsl:choose>
<xsl:when test="price&gt;'15'">
<td bgcolor="#ff0000">
<xsl:value-of select="author"/></td>
</xsl:when>
<xsl:otherwise>
<td><xsl:value-of select="author"/></td>
</xsl:otherwise>
</xsl:choose>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>

</xsl:stylesheet>

Example 2

Declare a variable named "color". Set its value to the color attribute of the current element. If the current element has no color attribute, the value of "color" will be "blue":

<xsl:variable name="color">
<xsl:choose>
<xsl:when test="@color">
<xsl:value-of select="@color"/>
</xsl:when>
<xsl:otherwise>blue</xsl:otherwise>
</xsl:choose>
</xsl:variable>