在XSLT中,xsl:for-each
是一种循环结构,可以用来遍历XML文档中的不同部分。要从XML文档的不同部分嵌套xsl:for-each
,可以按照以下步骤操作:
<category name="fiction">
<book>
<title>Book 1</title>
<author>Author 1</author>
</book>
<book>
<title>Book 2</title>
<author>Author 2</author>
</book>
</category>
<category name="non-fiction">
<book>
<title>Book 3</title>
<author>Author 3</author>
</book>
<book>
<title>Book 4</title>
<author>Author 4</author>
</book>
</category>
</books>
xsl:for-each
遍历XML文档中的不同部分。例如,要遍历所有的category
元素,可以使用以下代码:<xsl:for-each select="category">
<!-- 在此处编写针对每个category元素的处理代码 -->
</xsl:for-each>
xsl:for-each
循环内部,可以继续使用xsl:for-each
遍历每个category
元素的子元素。例如,要遍历每个category
元素下的所有book
元素,可以使用以下代码:<xsl:for-each select="category">
<xsl:for-each select="book">
<!-- 在此处编写针对每个book元素的处理代码 -->
</xsl:for-each>
</xsl:for-each>
xsl:for-each
循环中,可以使用XPath表达式访问每个book
元素的属性,例如title
和author
。完整的XSLT样式表可能如下所示:<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>Books</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th style="text-align:left">Title</th>
<th style="text-align:left">Author</th>
</tr>
<xsl:for-each select="books/category">
<xsl:for-each select="book">
<tr>
<td>
<xsl:value-of select="title"/>
</td>
<td>
<xsl:value-of select="author"/>
</td>
</tr>
</xsl:for-each>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
这个XSLT样式表将生成一个HTML表格,其中包含了XML文档中所有书籍的标题和作者。通过使用嵌套的xsl:for-each
循环,可以遍历XML文档的不同部分,并根据需要处理每个元素。
领取专属 10元无门槛券
手把手带您无忧上云