Phần tử XSLT <xsl:choose>
Phần tử <xsl:choose> được sử dụng cùng với <xsl:when> và <xsl:otherwise> để thể hiện nhiều bài kiểm tra có điều kiện.
Phần tử <xsl:choose>
Cú pháp
<xsl:choose>
<xsl:when test=" expression ">
... some output ...
</xsl:when>
<xsl:otherwise>
... some output ....
</xsl:otherwise>
</xsl:choose>
Nơi đặt Điều kiện Chọn
Để chèn một bài kiểm tra nhiều điều kiện vào tệp XML, hãy thêm các phần tử <xsl:choose>, <xsl:when> và <xsl:otherwise> vào tệp XSL:
Ví dụ
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="https://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">
<tr>
<td><xsl:value-of select="title"/></td>
<xsl:choose>
<xsl:when test="price > 10">
<td bgcolor="#ff00ff">
<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>
Hãy tự mình thử »Đoạn mã trên sẽ thêm màu nền hồng vào cột "Nghệ sĩ" KHI giá CD cao hơn 10.
Một vi dụ khac
Đây là một ví dụ khác chứa hai phần tử <xsl:when>:
Ví dụ
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="https://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">
<tr>
<td><xsl:value-of select="title"/></td>
<xsl:choose>
<xsl:when test="price > 10">
<td bgcolor="#ff00ff">
<xsl:value-of select="artist"/></td>
</xsl:when>
<xsl:when test="price > 9">
<td bgcolor="#cccccc">
<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>
Hãy tự mình thử »Đoạn mã trên sẽ thêm màu nền hồng vào cột "Nghệ sĩ" KHI giá CD cao hơn 10 và màu nền xám KHI giá CD cao hơn 9 và thấp hơn hoặc bằng 10.