HOW TO display ANY "flat XML" file as a HTML table using generic XSL stylesheet

In response to a forum posting, I adapted the XSL code in the article "Convert XML To an Excel Spreadsheet Using XSL" to display ANY "flat XML" file (like the one used in the examples in W3Schools) as a HTML table with this generic XSL stylesheet -

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<HTML>
<BODY>
<xsl:apply-templates/>
</BODY>
</HTML>
</xsl:template>

<xsl:template match="/*">
<TABLE BORDER="1">
<TR>
<xsl:for-each select="*[position() = 1]/*">
<TD>
<xsl:value-of select="local-name()"/>
</TD>
</xsl:for-each>
</TR>
<xsl:apply-templates/>
</TABLE>
</xsl:template>

<xsl:template match="/*/*">
<TR>
<xsl:apply-templates/>
</TR>
</xsl:template>

<xsl:template match="/*/*/*">
<TD>
<xsl:value-of select="."/>
</TD>
</xsl:template>

</xsl:stylesheet>



To try it out, copy the code into a text file and name it as generic.xsl

Throw in this line into your flat XML file right after the XML declaration -

<?xml-stylesheet type="text/xsl" href="generic.xsl"?>


One cool feature in Firefox is that you can view rendered source of a desired portion of the web page by choosing "View Selection Source" from the context menu. I found this feature useful while debugging the stylesheet.

Comments