องค์ประกอบ <xsl:when> ของ XSLT

การระบุและการใช้งาน

<xsl:when> องค์ประกอบใช้เพื่อกำหนดกระบวนการที่เกี่ยวข้องกับ <xsl:choose> องค์ประกอบ

<xsl:when> องค์ประกอบคำนวณอุปสาหรงค์ หากกลับมาเป็น true จะปฏิบัติตามกระบวนการที่กำหนด

หมายเหตุ:<xsl:when> องค์ประกอบสนับสนุนหลายเงื่อนไขของ <xsl:choose> และ <xsl:otherwise> องค์ประกอบ

ระบุ

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

ขอบเขต

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

ตัวอย่าง

ตัวอย่าง 1

หลังจากนี้ความสัมพันธ์ใน cd จะมีสีส่วนที่จะแสดง artist หาก price มากกว่า 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" จะมีค่า "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>