XSL – Transformation
Transforming XML to HTML
What if you want to transform the following XML document (open it with IE5) into HTML?
<?xml version="1.0" encoding="ISO8859-1" ?> <CATALOG> <CD> <TITLE>Empire Burlesque</TITLE> <ARTIST>Bob Dylan</ARTIST> <COUNTRY>USA</COUNTRY> <COMPANY>Columbia</COMPANY> <PRICE>10.90</PRICE> <YEAR>1985</YEAR> </CD> |
Consider the following XSL document (open it with IE5) as an HTML template to populate a HTML document with XML data:
<?xml version='1.0'?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl"> <xsl:template match="/"> <html> <body> <table border="2" bgcolor="yellow"> <tr> <th>Title</th> <th>Artist</th> </tr> <xsl:for-each select="CATALOG/CD"> <tr> <td><xsl:value-of select="TITLE"/></td> <td><xsl:value-of select="ARTIST"/></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> |
In the above file, the xsl:for-each element locates elements in the XML document and repeats a template for each one. The select attribute describes the element in the source document. The syntax for this attribute is called an XSL Pattern, and works like navigating a file system where a forward slash (/) selects subdirectories. The xsl:value-of element selects a child in the hierarchy and inserts the content of that child into the template.
Since an XSL style sheet is an XML file itself, the file begins with an xml declaration. The xsl:stylesheet element indicates that this document is a style sheet. The template has also been wrapped with xsl:template match=”/” to indicate that this is a template that corresponds to the root (/) of the XML source document.
If you add a reference to the above stylesheet to your original XML document (look at line 2), your browser will nicely transform your XML document into HTML (open it in IE5):
<?xml version="1.0" encoding="ISO8859-1" ?> <?xml-stylesheet type="text/xsl" href="cd_catalog.xsl"?> <CATALOG> <CD> <TITLE>Empire Burlesque</TITLE> <ARTIST>Bob Dylan</ARTIST> <COUNTRY>USA</COUNTRY> <COMPANY>Columbia</COMPANY> <PRICE>10.90</PRICE> <YEAR>1985</YEAR> </CD> |