我有以下XML:
<RECORDS>
<RETREC>
<heading>Green Fruits</heading>
<message>Kiwi</message>
</RETREC>
<RETREC>
<heading>Green Fruits</heading>
<message>Apple</message>
</RETREC>
<RETREC>
<heading>Red Fruits</heading>
<message>Apple</message>
</RETREC>
<RETREC>
<heading>Red Fruits</heading>
<message>Strawberry</message>
</RETREC>
</RECORDS>
我想创建一个XSLT 1.0模板来获取此HTML:
<table>
<tr><th>Green Fruits</th></tr>
<tr><td>Kiwi</td></tr>
<tr><td>Apple</td></tr>
<tr><th>Red Fruits</th></tr>
<tr><td>Apple</td></tr>
<tr><td>Strawberry</td></tr>
</table>
到目前为止,我是根据另一篇Stack Overflow帖子获得的,但是我找不到与原始数据匹配的结构,而且我对它的理解还不足以知道如何修改它才能正常工作
<?xml version="1.0" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:key name="heading" match="RECORDS" use="@heading" />
<xsl:template match="/">
<div>
<xsl:choose>
<xsl:when test="count(/RECORDS/RETREC)>=1">
<body>
<center>
<table>
<xsl:template match="RECORDS">
<xsl:apply-templates select="/RETREC/heading[generate-id(.)=generate-id(key('heading',@heading)[1])]"/>
</xsl:template>
<xsl:template match="heading">
<xsl:for-each select="key('heading', @heading)">
<tr>
<th align="center"><xsl:value-of select="heading" disable-output-escaping="yes"/></th>
</tr>
<xsl:for-each select="RETREC">
<tr>
<td align="center"><xsl:value-of select="message" disable-output-escaping="yes"/></td>
</tr>
</xsl:for-each>
</xsl:for-each>
<tr>
<td> </td> <!-- Adds a blank line in between heading -->
</tr>
</xsl:template>
</table>
</center>
</body>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="/text()"/>
<p id="No_return">No Records</p>
</xsl:otherwise>
</xsl:choose>
</div>
</xsl:template>
</xsl:stylesheet>
答案 0 :(得分:3)
您显示的输出可以简单地通过以下方式生成:
XSlT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:key name="heading" match="RETREC" use="heading" />
<xsl:template match="/RECORDS">
<table>
<xsl:for-each select="RETREC[generate-id(.)=generate-id(key('heading', heading)[1])]">
<tr>
<th>
<xsl:value-of select="heading"/>
</th>
</tr>
<xsl:for-each select="key('heading', heading)">
<tr>
<td>
<xsl:value-of select="message" />
</td>
</tr>
</xsl:for-each>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>