Reputation: 470
I've got this 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>
And I want to create a XSLT 1.0 template to get this 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>
I've got this so far based on another Stack Overflow post but I haven't been able to find one where the original data matches this structure, and I don't understand it enough to know how to modify it to work.
<?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>
Upvotes: 0
Views: 36
Reputation: 116992
The output you show can be generated simply by:
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>
Upvotes: 3