XSLT <xsl:for-each> 元素

定义和用法

<xsl:for-each> 元素可遍历指定的节点集中的每个节点。

语法

<xsl:for-each
select="expression">
<!-- Content:(xsl:sort*,template) -->
</xsl:for-each>

属性

属性值描述
selectexpression必需。被处理的节点集。

实例

例子 1

循环遍历每个 "cd" 元素,并使用 <xsl:value-of> 把每个 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">
<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>

查看 XML 文件,查看 XSL 文件,查看结果。

例子 2

循环遍历每个 "cd" 元素,并使用 <xsl:value-of> 把每个 title 和 artist 写到输出中(以 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:sort select="artist"/>
<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>

查看 XML 文件,查看 XSL 文件,查看结果。