ล่าสุดการพัฒนาเว็บบทเรียน
 

XSLT <xsl:choose> Element


<อ้างอิงองค์ประกอบ XSLT

ความหมายและการใช้งาน

<xsl:choose> องค์ประกอบที่จะใช้ร่วมกับ <xsl:when> และ <xsl:otherwise> จะแสดงการทดสอบหลายเงื่อนไข

ถ้าไม่มี <xsl:when> เป็นความจริงเนื้อหาของ <xsl:otherwise> มีการประมวลผล

ถ้าไม่มี <xsl:when> เป็นความจริงและไม่มี <xsl:otherwise> องค์ประกอบที่มีอยู่ไม่มีอะไรที่จะถูกสร้างขึ้น

Tip: สำหรับการทดสอบเงื่อนไขง่ายใช้ <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 &gt; 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>
ลองตัวเอง»

ประกาศตัวแปรชื่อ "color" ตั้งความคุ้มค่ากับ color แอตทริบิวต์ขององค์ประกอบปัจจุบัน ถ้าองค์ประกอบปัจจุบันมีแอตทริบิวต์ไม่มีสีค่าของ "color" จะเป็น "green" :

<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