Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

XSLT <xsl:if> elements


May 28, 2021 XSL T


Table of contents


XSLT and lt;xsl: if.gt; elements

Only when a given condition is met can you use the template in the XSLT-lt;xsl:if-gt; element!


XSLT <xsl:if> elements XSLT element reference manual

Definitions and usages

The element contains a template that is applied only if the specified condition is true.

Tip: Please use it in collaboration with slt;xsl:choose> and slt;xsl:otherwise> to express multiple conditional testing!


Grammar

<xsl:if
test="expression">

<!-- Content: template -->

</xsl:if>

Property

Attributes value describe
test expression Required.The conditions to be tested.


When the price of the CD is higher than 10, choose the values of title and artist:

Instance 1

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<xsl:if test="price > 10">
<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>

Displays the title of each CD. I f it is not the last or penultimate CD, insert ", " between each CD-title. I f it's the last CD, add "!" after the title. If it's the penultimate CD, add ", and" after the title:

Instance 2

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<p>Titles:
<xsl:for-each select="catalog/cd">
<xsl:value-of select="title"/>
<xsl:if test="position()!=last()">
<xsl:text>, </xsl:text>
</xsl:if>
<xsl:if test="position()=last()-1">
<xsl:text> and </xsl:text>
</xsl:if>
<xsl:if test="position()=last()">
<xsl:text>!</xsl:text>
</xsl:if>
</xsl:for-each>
</p>
</body>
</html>
</xsl:template>

</xsl:stylesheet>



XSLT <xsl:if> elements XSLT element reference manual