XSLT <xsl:choose>
❮ การอ้างอิงองค์ประกอบ XSLT
ความหมายและการใช้งาน
<xsl:choose> องค์ประกอบใช้ร่วมกับ <xsl:เมื่อ> และ <xsl:otherwise> เพื่อแสดงการทดสอบแบบมีเงื่อนไขหลายรายการ
หากไม่มี <xsl:เมื่อ> เป็นจริง เนื้อหาของ <xsl:otherwise> จะถูกประมวลผล
หากไม่มี <xsl:เมื่อ> เป็นจริง และไม่มีองค์ประกอบ <xsl:otherwise> แสดงว่าไม่มีอะไรถูกสร้างขึ้น
เคล็ดลับ:สำหรับการทดสอบตามเงื่อนไขอย่างง่าย ให้ใช้ <xsl:if> องค์ประกอบแทน
ไวยากรณ์
<xsl:choose>
<!-- Content:(xsl:when+,xsl:otherwise?) -->
</xsl:choose>
คุณลักษณะ
ไม่มี
ตัวอย่าง
รหัสด้านล่างจะเพิ่มสีพื้นหลังสีชมพูให้กับคอลัมน์ศิลปิน เมื่อราคาของซีดีสูงกว่า 10
ตัวอย่าง
<?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>
ประกาศตัวแปรชื่อ "สี" ตั้งค่าเป็นแอตทริบิวต์สีขององค์ประกอบปัจจุบัน หากองค์ประกอบปัจจุบันไม่มีแอตทริบิวต์สี ค่าของ "สี" จะเป็น "สีเขียว":
<xsl:variable name="color">
<xsl:choose>
<xsl:when test="@color">
<xsl:value-of select="@color"/>
</xsl:when>
<xsl:otherwise>green</xsl:otherwise>
</xsl:choose>
</xsl:variable>
❮ การอ้างอิงองค์ประกอบ XSLT