XML: Create HTML table using XSLT
To create HTML table using XSLT for XML documents we will use XSLT element "xsl:for-each". See sample here.
records.xml
|
<?xml version="1.0" encoding="UTF-8" ?> <?xml-stylesheet href="styles.xsl" type="text/xsl" ?> <collection> <book> <author year= "1990" > John Doe </author> <title> JavaScript </title> <price> 10.99 </price> </book> <book> <author year= "2000" > Mary Jones </author> <title> Photoshop Secrets </title> <price> 15.99 </price> </book> <book> <author year= "2005" > Garry Po </author> <title> PHP Programming </title> <price> 20.99 </price> </book> </collection> |
Now let's create XSL file that will hold "for-each" element to create the HTML table.
styles.xsl
|
<?xml version="1.0" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<!-- / forward slash is used to denote a patern that matches the root node of the XML document --> <xsl:template match ="/" > <html> <head> <title> Book Collection </title> </head> <body> <xsl:apply-templates /> </body> </html> </xsl:template>
<xsl:template match="collection" > <table width="400" border="1" > <tr bgcolor = "#cccccc" > <td>Author</td> <td>Year</td> <td>Name</td> <td>Price</td> </tr> <xsl:for-each select="book" > <tr> <td> <xsl:value-of select="author" /> </td> <!-- here we use /@ to access the value of an attribute --> <td> <xsl:value-of select="author/@year" /> </td> <td> <xsl:value-of select="title" /> </td> <td> <xsl:value-of select="price" /> </td> </tr> </xsl:for-each> </table> </xsl:template > </xsl:stylesheet > |
As you can see using XSLT to create HTML table is very simple. The key element in this little tutorial is the "for-each" statement.