ตัวแทน <xsl:if> XSLT

คำหมายและวิธีใช้

<xsl:if> มีเทมเพลตหนึ่ง ซึ่งจะนำเอาเทมเพลตนี้เมื่อเงื่อนไขที่กำหนดเกิดขึ้นเท่านั้น

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

ภาษาเขียน

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

รายการ

รายการ ค่า คำอธิบาย
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 ทุกตัว. หากเป็น CD หลังสุด ให้ใส่ "!" หลังชื่อ. หากเป็น CD ก่อนหลังสุด ให้ใส่ ", and " หลังจาก CD นั้น:

<?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> และ </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>