3. XSL--Implementation on the Client
Solution
In the above chapter we have explained how XSL converts XML into HTML files. The method is to add an XSL stylesheet information to the head of the XML document and then let the browser perform the conversion process.
This method does a good job in most cases, but it won't be displayed correctly in browsers that don't support XML.
A better and more comprehensive solution is to use Javascript to implement XML to HTML conversion. However, using JavaScript must be supported by the following functions:
a. Allow Javascript to replace the browser for detailed detection;
b. Use different style sheets according to different needs and different browsers.
This is completely feasible for XSL. One of the goals of designing XSL is to allow one format to be converted into another, support different browsers, and support different user needs. The important task of future browsers is to perform XSL conversion work on the client side.
2. A specific example
Here is some code for an example of an XML document (cd_catalog.xml) mentioned above:
<?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>
.
.
.
Here is the complete XSL file (cd_catalog.xsl):
<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl="http:///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>
Note that the XML file has not been added to the XSL style sheet yet and has not been converted into an HTML file.
Here is the HTML code to implement the final conversion using JavaScript:
<html>
<body>
<script language="javascript">
// Load XML
var xml = new ActiveXObject("")
= false
("cd_catalog.xml")
// Load the XSL
var xsl = new ActiveXObject("")
= false
("cd_catalog.xsl")
// Transform
((xsl))
</script>
</body>
</html>
Javascript is used in the above code. If you don't know how to write JavaScript, you'd better learn it specifically.
The first piece of code creates an object parsed by Microsoft Parser (XMLDOM) and reads the XML document into memory; the second piece of code creates another object and imports the XSL document; the last line of code converts the XML document into an XSL document and outputs the result to the HTML file.