我正在尝试转换具有多个同名子节点的XML文件。当我运行for-each
循环来转换XML标记时,只打印每个双节点中的第一个。我需要使用嵌套循环吗?如果是这样,因为我尝试过这会导致错误。这是我的XSLT语法:
<xsl:template match="/">
<html>
<head>
<link rel="stylesheet" type="text/css" href="cdcatalog.css" />
</head>
<body>
<h2>CD Catalog</h2>
<table>
<tr>
<th>Band</th>
<th>Title</th>
<th>Rating</th>
<th>Year</th>
<th>Date</th>
</tr>
<xsl:for-each select="catalog/band">
<tr>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="cd/title"/></td>
<td><xsl:value-of select="cd/rating"/></td>
<td><xsl:value-of select="cd/yearReleased"/></td>
<td><xsl:value-of select="cd/dateAcquired"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
这是我的XML标记;正如您所看到的,每个乐队都有多张CD,但只打印了每个乐队的第一张CD:
<catalog>
<band>
<name>Aloha</name>
<based>Cleveland, OH</based>
<active>true</active>
<cd>
<title>That's Your Fire</title>
<label>Polyvinyl</label>
<numTracks>10</numTracks>
<rating>9</rating>
<yearReleased>2000</yearReleased>
<dateAcquired>12/25/02</dateAcquired>
</cd>
<cd>
<title>Sugar</title>
<label>Polyvinyl</label>
<numTracks>10</numTracks>
<rating>9</rating>
<yearReleased>2002</yearReleased>
<dateAcquired>12/25/07</dateAcquired>
</cd>
</band>
</catalog>
提前多多感谢!
答案 0 :(得分:2)
您正在为每个频段创建一行,而不是为每个 cd 创建一行。试试这种方式:
<xsl:template match="/">
<html>
<head>
<link rel="stylesheet" type="text/css" href="cdcatalog.css" />
</head>
<body>
<h2>CD Catalog</h2>
<table>
<tr>
<th>Band</th>
<th>Title</th>
<th>Rating</th>
<th>Year</th>
<th>Date</th>
</tr>
<xsl:for-each select="catalog/band/cd">
<tr>
<td><xsl:value-of select="../name"/></td>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="rating"/></td>
<td><xsl:value-of select="yearReleased"/></td>
<td><xsl:value-of select="dateAcquired"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>