XSLT <xsl:if>
❮ การอ้างอิงองค์ประกอบ XSLT
ความหมายและการใช้งาน
องค์ประกอบ <xsl:if> มีเทมเพลตที่จะนำไปใช้ก็ต่อเมื่อเงื่อนไขที่ระบุเป็นจริงเท่านั้น
เคล็ดลับ:ใช้ <xsl:choose> ร่วมกับ <xsl:when> และ <xsl:otherwise> เพื่อแสดงการทดสอบแบบมีเงื่อนไขหลายรายการ!
ไวยากรณ์
<xsl:if
test="expression">
<!-- Content: template -->
</xsl:if>
คุณลักษณะ
Attribute | Value | Description |
---|---|---|
test | expression | Required. Specifies the condition to be tested |
ตัวอย่าง
เลือกค่าชื่อและศิลปิน IF ราคาของซีดีสูงกว่า 10:
ตัวอย่าง 1
<?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">
<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>
แสดงชื่อของแต่ละซีดี ใส่ ", " ระหว่างชื่อซีดีแต่ละแผ่น ถ้าไม่ใช่ซีดีแผ่นสุดท้ายหรือแผ่นสุดท้าย แต่เป็นแผ่นเดียว ถ้าเป็นซีดีแผ่นสุดท้าย ให้เติม "!" ด้านหลังชื่อเรื่อง หากเป็นแผ่นสุดท้ายแต่เพียงแผ่นเดียว ให้เพิ่ม ", และ " ด้านหลังชื่อ:
ตัวอย่าง 2
<?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>
<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>
❮ การอ้างอิงองค์ประกอบ XSLT