In a previous article, we learned that CSS can be applied to both XML and HTML documents to indicate how you want those documents to look in a Web browser. But what do we do if we need more power than CSS provides? Or what if you've created an XML document that isn't set up in a way that CSS can be applied to.
This is where eXtensible Stylesheet Language for Transformations (XSLT) comes in. Using XSLT, you can transform an XML document into any text-based format, including HTML, plain text, or another schema of XML.
For example, if you take a simple XML document:
<?xml version="1.0"?>
<greeting>Hello world.</greeting>
Save this file as
helloworld.xml
To convert it to an HTML document, you might write an XSLT document file that looks like this:
<?xml version="1.0"?>
<html xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xsl:version="1.0">
<head>
<title>Hello World</title>
</head>
<body>
<p>
I just want to say <b><xsl:value-of select="greeting"/></b>
</p>
</body>
</html>
Save this file as
hellotohtml.xsl
There are only two instances of XSLT in the above file. In the <html> tag you define the XML namespace and version used. This isn't used for transformation but more for informational purposes. Then in the body of the HTML document, there is a line
<xsl:value-of select="greeting"/>
This is the only transformation in the document.
The transformation says to look for any instance of the XML tag <greeting> and place the information stored in that tag (the value) in the HTML document.
But right now, all we have are two files:
- helloworld.xml
- hellotohtml.xsl
<html xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xsl:version="1.0">
<head>
<title>Hello World</title>
</head>
<body>
<p>
I just want to say <b>Hello world.</b>
</p>
</body>
</html>
Note: the spacing of the text file will not be exactly the same as above.
But it's one thing to add one line from an XML document into an HTML document. After all, it takes longer to actually write the XSLT document and running the parser than it would to simply write the HTML. You can also earn how you can apply the same XSLT processing power to convert a more complex document.

