ตัวแทน <xsl:choose> ของ XSLT
- 上一頁 XSLT <if>
- 下一頁 XSLT Apply
XSLT <xsl:choose> องค์ประกอบสำหรับผสม <xsl:when> และ <xsl:otherwise> ในการแสดงทดสอบเงื่อนไขหลายรายการ。
<xsl:choose> อิเล็ม
การใช้งานภาษาบทเขียน
<xsl:choose> <xsl:when test="expression"> ... ออกทางหลัง ... </xsl:when> <xsl:otherwise> ... ออกทางหลัง ... </xsl:otherwise> </xsl:choose>
ที่ไหนที่จะจัดเก็บเงื่อนไขเลือก
เพื่อใส่การทดสอบเงื่อนไขเพิ่มเติมสำหรับไฟล์ XML โปรดเพิ่ม <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>
上面的代碼會在 CD 的價格高於 10 時向 "Artist" 列添加粉色的背景顏色,並在 CD 的價格高於 9 且低於等於 10 時向 "Artist" 列添加灰色的背景顏色。
上面的轉換結果類似這樣:

- 上一頁 XSLT <if>
- 下一頁 XSLT Apply