Pages

Friday, February 09, 2007

The Basic of XSLT Transformation

From the early student year up until now I always learn anything new in programming with the help of some examples. XSLT Transformation is one of them. It's not a new technology but if you can master this, a lot of things can be done. As for me I use it to organize the XML generated data so that it can appear nicely on the web. So here are some basic guide for this.

XML Document
Let's start this with creating XML document so that we can transform into XHTML format.

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="shopping.xsl"?>
<shopping>
<item>
<name>Paper Clip</name>
<price>00.90</price>
</item>
<item>
<name>AAA Paper</name>
<price>10.90</price>
</item>
<item>
<name>Glue</name>
<price>3.90</price>
</item>
<item>
<name>Cutter</name>
<price>2.50</price>
</item>
<item>
<name>Pen</name>
<price>6.99</price>
</item>
</shopping>


Save this as shopping.xml

Create an XSL Style Sheet
Next we create the XSL Style Sheet ("shopping.xsl") with a transformation template:

<?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>
<h2>My Shopping List</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th align="left">Item Name</th>
<th align="left">Price ($)</th>
</tr>
<xsl:for-each select="shopping/item">
<tr>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="price"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Load the shopping.xml from your favorite browser and it's done.

P/S: Try play around with the shopping.xsl XSL transformation file.

No comments: