element <xsl:when> ของ XSLT

การระบุและวิธีใช้

element <xsl:when> ใช้เพื่อกำหนดการปฏิบัติที่เกี่ยวข้องกับ element <xsl:choose>。

element <xsl:when> จะคำนวณสัญญาณหนึ่ง และจะปฏิบัติการที่กำหนดแก่นั้น หากมีการกลับค่า true。

หมายเหตุ:element <xsl:when> ให้ความเห็นด้วยหลายข้อเงื่อนไขที่เกี่ยวข้องกับ element <xsl:choose> และ element <xsl:otherwise>。

ภาษา

<xsl:when test="boolean-expression">
  <!-- Content: template -->
</xsl:when>

รายละเอียด

รายละเอียด ค่า รายละเอียด
test boolean-expression สำคัญ กำหนดการแสดงที่ต้องการทดสอบ

ตัวอย่าง

ตัวอย่าง 1

รหัสใต้คำสั่งนี้จะเพิ่มสีหลังแดงชมพูให้กับคอลัมน์ artist ขณะที่ราคา cd สูงกว่า 10:

<?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>

ดูไฟล์ XMLดูไฟล์ XSLดูผลลัพธ์

ตัวอย่าง 2

ประกาศแปลงค่าที่มีชื่อว่า "color" และกำหนดค่าให้กับอัตราแบบ 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>