How to display XML elements in a HTML table using XSLT?
Create an XML document.
<?xml version=”1.0″?>
<?xml-stylesheet type=”text/xsl” href=”books04.xsl”?>
<books>
<book>
<title>OpenGL Programming Guide Fourth Edition</title>
<location>107</location>
<publisher>Addison-Wesley</publisher>
<year>2004</year>
</book>
<book>
<title>Curves and Surfaces for CAGD: A Practical Guide</title>
<location>116</location>
<publisher>Academic Press</publisher>
<year>2002</year>
</book>
<book>
<title>An Introduction to NURBS: With Historical Perspective</title>
<location>120</location>
<publisher>Academic Press</publisher>
<year>2001</year>
</book>
<book>
<title>NURBS: From Projective Geometry to Practical Use</title>
<location>126</location>
<publisher>A K Peters</publisher>
<year>1999</year>
</book>
</books>
Create an XSL stylesheet.
<?xml version=”1.0″?>
<xsl:stylesheet version=”1.0″ xmlns_xsl=”http://www.w3.org/1999/XSL/Transform“>
<xsl:output method=”html” encoding=”UTF-8″/>
<xsl:template match=”/”>
<html>
<head><title>Books</title>
</head>
<body>
<table width=”100%” border=”1″>
<THEAD>
<TR>
<TD width=”35%”><B>Title</B></TD>
<TD width=”15%”><B>Location</B></TD>
<TD width=”10%”><B>Publisher</B></TD>
<TD width=”10%”><B>Year</B></TD>
</TR>
</THEAD>
<TBODY>
<xsl:for-each select=”books/book”>
<TR>
<TD width=”35%”><xsl:value-of select=”title” /></TD>
<TD width=”15%”><xsl:value-of select=”location” /></TD>
<TD width=”10%”><xsl:value-of select=”publisher” /></TD>
<TD width=”10%”><xsl:value-of select=”year” /></TD>
</TR>
</xsl:for-each>
</TBODY>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
To bind the XML elements to a HTML table, the <for-each> XSL template must appear before each table row tag. This ensures that a new row is created for each <book> element.
The <value-of> template will output the selected text of each child element into a separate table.