我有一个XML文件
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<state>USA</state>
</cd>
<cd>
<title>Hide your heart</title>
<artist>Bonnie Tyler</artist>
<country>UK</country>
</cd>
</catalog>
我正在编写一个XSLT文件来创建一个具有正确表Header的表。
当xsl:element= state
,表头应该是State
和xsl:element=Country
时,表头应该是country
。
<xsl:choose>
<tr>
<xsl:when test="element name='state'">
<tr>
<td>
<b>Collection </b>
</td>
<td>
<table border="1">
<tr>
<th>Artist</th>
<th>State</th>
</tr>
<tr>
<td>
<xsl:value-of select="artist" />
></td>
<td>
<xsl:value-of select="state" />
</td>
</tr>
</table>
</td>
</tr>
</xsl:when>
<xsl:when test="element name='country'">
<tr>
<td>
<b>Collection </b>
</td>
<td>
<table border="1">
<tr>
<th>Artist</th>
<th>Country</th>
</tr>
<tr>
<td>
<xsl:value-of select="artist" />
></td>
<td>
<xsl:value-of select="country" />
</td>
</tr>
</table>
</td>
</tr>
</xsl:when>
<xsl:otherwise>
<xsl:text>Error</xsl:text>
</xsl:otherwise>
</tr>
</xsl:choose>
基本上我需要使用if或when xml元素的条件
你的XPath <xsl:when...>
表达式错了。您使用<xsl:when test="element name='state'">
而不是正确的
<xsl:when test="state">
测试是否存在作为state
元素的子元素的<cd>
元素。第二个<xsl:when...>
也出现了同样的错误。
因此,使用这些XSLT模板进行正确的输出:
<xsl:template match="/catalog" > <!-- only for completeness of illustration -->
<table border="1">
<xsl:apply-templates />
</table>
</xsl:template>
<xsl:template match="cd" > <!-- will be applied to all <cd> elements -->
<tr>
<xsl:choose>
<xsl:when test="state">
<tr>
<td>
<b>Collection 1</b>
</td>
<td>
<table border="1">
<tr>
<th>Artist</th>
<th>State</th>
</tr>
<tr>
<td>
<xsl:value-of select="artist" />
></td>
<td>
<xsl:value-of select="state" />
</td>
</tr>
</table>
</td>
</tr>
</xsl:when>
<xsl:when test="country">
<tr>
<td>
<b>Collection 2</b>
</td>
<td>
<table border="1">
<tr>
<th>Artist</th>
<th>Country</th>
</tr>
<tr>
<td>
<xsl:value-of select="artist" />
></td>
<td>
<xsl:value-of select="country" />
</td>
</tr>
</table>
</td>
</tr>
</xsl:when>
<xsl:otherwise>
<xsl:text>Error</xsl:text>
</xsl:otherwise>
</xsl:choose>
</tr>
</xsl:template>
输出: