核心標籤
1. <xsl:value-of>
作用:擷取指定XML節點的文字內容,輸出到結果文件。
<!-- 直接取出第一個catalog/cd底下title的值(沒有迴圈只會取得第一筆) -->
<xsl:value-of select="catalog/cd/title" />Code language: HTML, XML (xml)
沒有搭配<xsl:for-each>迴圈時,只會比對第一個節點,無法遍歷全部資料。
2. <xsl:for-each>
作用:迴圈走訪一組符合條件的XML節點,批量處理多筆資料。
<xsl:for-each select="class/student">
<li><xsl:value-of select="name"/>;<xsl:value-of select="age"/></li>
</xsl:for-each>Code language: HTML, XML (xml)
XPath過濾語法
在select路徑後面使用[條件]篩選節點,實現資料過濾
<!-- 只輸出artist等於Bob Dylan的cd記錄 -->
<xsl:for-each select="catalog/cd[artist='Bob Tom']">Code language: HTML, XML (xml)
支援的運算子
| 運算子 | XPath寫法 | 含義 |
|---|---|---|
| = | = | 等於 |
| != | != | 不等於 |
| < | < | 小於(不能直接寫<,必須轉義) |
| > | > | 大於(不能直接寫>,必須轉義) |
例如篩選價格小於10的CD
<xsl:for-each select="catalog/cd[price < 10]">Code language: HTML, XML (xml)
前面範例
student.xsl
<?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>
<head>
</head>
<body>
<ul>
<!-- 遍歷所有student節點 -->
<xsl:for-each select="class/student">
<li><xsl:value-of select="name"/>;<xsl:value-of select="age"/></li>
</xsl:for-each>
</ul>
</body>
</html>
</xsl:template>
</xsl:stylesheet>Code language: HTML, XML (xml)
對應XML(student.xml)
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="student.xsl"?>
<class>
<student>
<name>Jack</name>
<age>16</age>
</student>
<student>
<name>Jim</name>
<age>12</age>
</student>
</class>Code language: HTML, XML (xml)
增加過濾條件
只輸出年齡大於14歲的學生
<xsl:for-each select="class/student[age > 14]">
<li><xsl:value-of select="name"/>;<xsl:value-of select="age"/></li>
</xsl:for-each>Code language: HTML, XML (xml)
迴圈