One of the most common uses of XSLT (Extensible Stylesheet Language Transformations) is to convert XML to HTML. The reason for this is that XML can be used to store a certain amount of data. It is common to want to display this data on a web page.
<?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="planets.xsl"?> <planets> <planet> <name>Mercury</name> <radius>1,516</radius> <year>88</year> </planet> <planet> <name>Venus</name> <radius>3,760</radius> <year>225</year> </planet> <planet> <name>Earth</name> <radius>3,959</radius> <year>365</year> </planet> <planet> <name>Mars</name> <radius>2,106</radius> <year>687</year> </planet> </planets>
For this example, lets use the simple XML file shown above, which contains a small amount of data about the solar systems inner planets.
<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> </xsl:stylesheet>
Shown above is the basic template for an XSLT file. The firt line identifies it as XML, and the second line creates a stylesheet element and sets its namespace.
<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <body> <xsl:apply-templates/> </body> </html> </xsl:template> </xsl:stylesheet>
We add a template element, the match="/" attribute associates the template with the root of the XML source document, which matches the planets element in the XML file and adds the html and body elements.
<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <body> <xsl:apply-templates/> </body> </html> </xsl:template> <xsl:template match="planets"> <xsl:for-each select="planet"> <ul> <li><xsl:value-of select="name"/></li> <li><xsl:value-of select="radius"/></li> <li><xsl:value-of select="year"/></li> </ul> </xsl:for-each> </xsl:template> </xsl:stylesheet>
Next we add another template element which matches each planets element. To that template element we add a <xsl:for-each> element to iterate through the planet child nodes and replaces each with a UL (Unordered List) element. "name", "radius", and "year" and places them within a LI (List Item) elements.
<html> <body> <ul> <li>Mercury</li> <li>1,516</li> <li>88</li> </ul> <ul> <li>Venus</li> <li>3,760</li> <li>225</li> </ul> <ul> <li>Earth</li> <li>3,959</li> <li>365</li> </ul> <ul> <li>Mars</li> <li>2,106</li> <li>687</li> </ul> </body> </html>
When the XML file is processed against the XSLT file, the result is shown above. This is an html document with three Unordered List elements, the list items display the "name", "radius", and "year" values of each planet in a bulleted list.