XSLT transformation
#Case study: How to use XSLT to convert XML to XHTML.
We will explain the details of this example in the next chapter.
Correct Style Sheet Declaration
The root element of a document declared as an XSL style sheet is <xsl:stylesheet> or <xsl:transform>.
Note: <xsl:stylesheet> and <xsl:transform> are completely synonymous and can be used!
According to the W3C's XSLT standard, the correct way to declare an XSL style sheet is:
xmlns:xsl="http: //www.w3.org/1999/XSL/Transform">
Or:
xmlns :xsl="http://www.w3.org/1999/XSL/Transform">
To access XSLT elements, attributes and characteristics, we must declare the XSLT name at the top of the document space.
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" points to the official W3C XSLT namespace. If you use this namespace, you must include the attribute version="1.0".
Start with a raw XML document
We now want to convert the following XML document ("cdcatalog.xml")to XHTML:
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
.
.
</catalog>
View XML files in Firefox and Internet Explorer: Open the XML file (usually by clicking on a link) - the XML document displays the root element and child elements in color code. Click the plus (+) or minus (-) sign to the left of an element to expand or collapse the element's structure. To view the original XML source file (without the plus and minus signs), select View Page Source or View Source in your browser menu.
View XML files in Netscape 6: Open the XML file, then right-click in the XML file and select "View Page Source". XML documents display root elements and child elements in color code.
View XML files in Opera 7: Open the XML file, then right-click in the XML file and select "Framework"/"View Source". XML documents will appear as plain text.
View "cdcatalog.xml"
Create XSL style sheet
Then create an XSL style sheet ("cdcatalog.xsl") with a transformation template:
<xsl:stylesheet version="1.0"
xmlns :xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<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>
View "cdcatalog.xsl"
Link the XSL stylesheet to the XML document
Add an XSL stylesheet reference to the XML document ("cdcatalog.xml"):
<?xml-stylesheet type="text/xsl" href=" cdcatalog.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>
.
.
</catalog>
If the browser you are using is XSLT-compatible, it will convert your XML smoothly Convert to XHTML.
View results
We will explain the details of the above example in the next chapter.