ตัวแปร <xsl:choose> ของ XSLT
- หน้าก่อนหน้า XSLT <if>
- หน้าต่อไป XSLT apply
องค์ประกอบ <xsl:choose> ใน XSLT ใช้เชื่อม <xsl:when> และ <xsl:otherwise> รวมกันเพื่อแสดงการทดสอบเงื่อนไขหลายข้อ。
<xsl:choose> องค์ประกอบ
ภาษาบวก
<xsl:choose> <xsl:when test="expression"> ... ออกประโยค ... </xsl:when> <xsl:otherwise> ... ออกประโยค ... </xsl:otherwise> </xsl:choose>
ที่ไหนที่จะใส่เงื่อนไขเลือก
เพื่อใส่การทดสอบเงื่อนไขมากกว่าหนึ่ง ให้เพิ่ม <xsl:choose> และ <xsl:when> และ <xsl:otherwise> สู่ไฟล์ XSL:
<?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"> <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>
รหัสด้านบนจะเพิ่มสีของพื้นที่หลังของคอนเทนเนอร์ "Artist" ให้เป็นสีชมพูเมื่อราคาของ CD สูงกว่า 10。
ผลลัพธ์การแปลงที่อยู่ด้านบนคล้ายนี้:

ตัวอย่างอื่นๆ
จะเป็นตัวอย่างอื่นๆที่มี <xsl:when> สองอัน:
<?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"> <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>
รหัสโค้ดนี้จะเพิ่มสีพิเศษสีชมพูเข้าในคอลัมน์ "Artist" เมื่อราคา CD สูงกว่า 10 และเพิ่มสีเงาเข้าในคอลัมน์ "Artist" เมื่อราคา CD สูงกว่า 9 และต่ำเท่ากับ 10。
ผลลัพธ์การแปลงที่อยู่ด้านบนคล้ายนี้:

- หน้าก่อนหน้า XSLT <if>
- หน้าต่อไป XSLT apply