XSLT <xsl:for-each> 元素
The <xsl:for-each> 元素允許您在 XSLT 中執行迴圈。
The <xsl:for-each> 元素
XSL <xsl:for-each> 元素可用於選擇指定節點集的每個 XML 元素。
示例
<?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>我的 CD 收藏</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>標題</th>
<th>藝術家</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
自己動手試一試 »
注意: select 屬性的值是一個 XPath 表示式。XPath 表示式的工作方式類似於導航檔案系統;其中正斜槓 (/) 選擇子目錄。
過濾輸出
我們還可以透過在 <xsl:for-each> 元素的 select 屬性中新增一個條件來過濾 XML 檔案中的輸出。
<xsl:for-each select="catalog/cd[artist='Bob Dylan']">
合法的過濾運算子有:
- = (等於)
- != (不等於)
- < 小於
- > 大於
看看調整後的 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>
<body>
<h2>我的 CD 收藏</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>標題</th>
<th>藝術家</th>
</tr>
<xsl:for-each select="catalog/cd[artist='Bob Dylan']">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
自己動手試一試 »