XSLT <xsl: select> Phần tử
Phần tử <xsl: select> được sử dụng cùng với <xsl: when> và <xsl: else> để thể hiện nhiều thử nghiệm có điều kiện.
Phần tử <xsl: select>
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 nhiều kiểm tra có điều kiện vào tệp XML, hãy thêm các phần tử <xsl: select>, <xsl: when> và <xsl: else> vào tệp XSL:
Thí dụ
<?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>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>
Đoạn mã trên sẽ thêm màu nền hồng vào cột "Nghệ sĩ" KHI giá của CD cao hơn 10.
Một vi dụ khac
Đây là một ví dụ khác có chứa hai phần tử <xsl: when>:
Thí dụ
<?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>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>
Đ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.