我想在HTML表格中显示XML内容。我使用以下(简化)代码来执行此操作:
<xsl:template match="/">
<xsl:apply-templates select="/products/product">
<xsl:sort select="populariteit" order="descending" data-type="number"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="product">
<xsl:if test="position()=1">
<table>
<tr>
<td>
<xsl:value-of select="title"/>
</td>
</tr>
</table>
</xsl:if>
</xsl:template>
使用以下(简化)XML:
<products>
<product>
<title>Title One</title>
<popularity>250</popularity>
</product>
<product>
<title>Title Two</title>
<popularity>500</popularity>
</product>
<product>
<title>Title Three</title>
<popularity>400</popularity>
</product>
</products>
它的作用是按“流行度”对列表进行排序,然后显示表格中第一个条目的标题(最受欢迎的)。
现在,我想要完成的是显示前两个热门项目的标题。但无论我尝试什么,XSLT都会在两个不同的表而不是一个中输出它们。
我尝试过这样的事情:
<xsl:template match="product">
<table>
<tr>
<td>
<xsl:if test="position()=1">
<xsl:value-of select="title"/>
</xsl:if>
<xsl:if test="position()=2">
<xsl:value-of select="title"/>
</xsl:if>
</td>
</tr>
</table>
</xsl:template>
但这会产生两个不同的表格;我希望标题在同一个表格中彼此相邻显示,同时还使用排序列表中的信息。
我想要的HTML输出是:
<table>
<tr>
<td>
Title Three Title Two
</td>
</tr>
</table>
重要的是我只使用一个XSL来生成此输出,因为我正在使用的软件存在某些限制。
答案 0 :(得分:2)
您需要将生成表格的代码放在另一个模板中,例如
<xsl:template match="/">
<table>
<tr>
<xsl:apply-templates select="/products/product">
<xsl:sort select="populariteit" order="descending" data-type="number"/>
</xsl:apply-templates>
</tr>
</table>
</xsl:template>
<xsl:template match="product">
<xsl:if test="position() < 3">
<td>
<xsl:value-of select="title"/>
</td>
</xsl:if>
</xsl:template>
这会将每个标题放在一个单独的单元格中,如果您希望在一个单元格中同时将td
结果元素移动到另一个模板,并且仅在模板中输出标题{ {1}}。