ตัวแปร <xsl:if> ของ XSLT

การใช้งานและการประกาศ

<xsl:if> มีโมดูลที่ถูกใช้งานเมื่อเงื่อนไขที่กำหนดเพียงเดียวเป็นความจริง

คำเตือน:ใช้ <xsl:choose> กับ <xsl:when> และ <xsl:otherwise> ด้วยกันเพื่อแสดงเงื่อนไขที่มีหลายชิ้น!

ภาษาบัญญัติ

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

attribute

attribute ค่า รายละเอียด
test expression สำคัญต้องการระบุเงื่อนไขที่ต้องทดสอบ

ตัวอย่าง

ตัวอย่าง 1

เมื่อราคา CD สูงกว่า 10 ให้เลือกค่าของ title และ artist:

<?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">
      <xsl:if test="price > 10">
        <tr>
          <td><xsl:value-of select="title"/></td>
          <td><xsl:value-of select="artist"/></td>
        </tr>
      </xsl:if>
      </xsl:for-each>
    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

ตรวจสอบไฟล์ XMLตรวจสอบไฟล์ XSLตรวจสอบผลลัพธ์

ตัวอย่าง 2

แสดงชื่อหัวของ CD ต่อไป。หากไม่ใช่ CD หลังสุดหรือเป็น CD ที่อยู่ท้ายที่สุด ให้ใส่ ", " ระหว่าง CD-title ต่าง ๆ หากเป็น CD หลังสุด ให้เพิ่ม "!" หลังจากชื่อหัวของ CD หากเป็น CD ที่อยู่ท้ายที่สุด ให้เพิ่ม ", and " หลังจากนั้น

<?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>
    <p>Titles:
    <xsl:for-each select="catalog/cd">
      <xsl:value-of select="title"/>
      <xsl:if test="position()!=last()">
        <xsl:text>, </xsl:text>
      </xsl:if>
      <xsl:if test="position()=last()-1">
        <xsl:text> and </xsl:text>
      </xsl:if>
      <xsl:if test="position()=last()">
        <xsl:text>!</xsl:text>
      </xsl:if>
    </xsl:for-each>
    </p>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>