我有一个 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元素的条件
答案 0 :(得分:2)
您的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>
<强>输出:强>