When we write XSLT stylesheets, we’ll use XSLT which defines a set of primitives used to describe a document transformation to tell the processor what to do, and we’ll use XPath which defines a syntax for describing locations in XML documents to tell the processor what document to do it to.
Stylesheet Structure
The general structure of an XSLT stylesheet looks like this:
<xsl:stylesheet version="1.0"
xmlns:xsl= "http://www.w3.org/1999/XSL/Transform">
<!-- optional top-level elements, such as: -->
<xsl:import href="..."/>
<xsl:param name="..."/>
<!-- set of template rules: -->
<xsl:template match="...">...</xsl:template>
<xsl:template match="...">...</xsl:template>
...
</xsl:stylesheet>
The document, or root, element of the stylesheet is xsl:stylesheet. Alternatively, you can use the xsl:transform element, which behaves exactly the same way. Which you use is a matter of personal preference. The XSLT namespace is http://www.w3.org/1999/XSL/Transform. The conventional namespace prefix is xsl, but any prefix can be used—provided that it binds to the XSLT namespace URI.
Example
Here’s an XSLT stylesheet that defines how to transform the XML document:
<?xml version="1.0"?>
<!-- greeting.xsl -->
<xsl:stylesheet version="1.0" xmlns:xsl= "http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="/">
<xsl:apply-templates select="greeting"/>
</xsl:template>
<xsl:template match="greeting">
<html>
<body>
<h1>
<xsl:value-of select="."/>
</h1>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
It can transform the following XML document into something we can view in an ordinary household browser:
<!-- greeting.xml -->
<greeting>
Hello, World!
</greeting>
if you’re using Microsoft’s MSXSL, type this command:
msxsl greeting.xml greeting.xsl -o greeting.html
This command transforms the document greeting.xml, using the templates found in the stylesheet greeting.xsl. The results of the transformation are written to the file greeting.html.
<html>
<body>
<h1>
Hello, World!
</h1>
</body>
</html>