Original: A Egil refsnes translation: Atzie
Three. xsl--implementation in the client
1.JavaScript Solution
In the previous section we have explained how XSL transforms XML into an HTML file. The method is to add an XSL stylesheet information to the header of the XML document, and then let the browser perform the conversion process.
This approach is well done in most cases, but cannot be displayed correctly in browsers that do not 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 features:
A. Allows JavaScript to be used instead of browsers for detail detection;
B. Use a different style sheet depending on your needs and different browsers.
This is entirely feasible for XSL. One of the goals of designing XSL is to allow one format to be converted to another format, to support different browsers, and to support different user requirements. The important task of future browsers is to perform XSL conversion work on the client.
2. A concrete example
Here is some of the code for an example of an XML document (Cd_catalog.xml) that we 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>
.
.
.
The following is the complete XSL file (cd_catalog.xsl):
<?xml version= ' 1.0 '?>
<xsl:stylesheet xmlns:xsl= "Http://www.w3.org/TR/WD-xsl" >
<xsl:template match= "/" >
<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>
</xsl:template>
</xsl:stylesheet>
Note that the XML file is not yet added to the XSL stylesheet and has not been converted to an HTML file.
The following is the HTML code to implement the final transformation with Javasript:
<body>
<script language= "JavaScript" >
Load XML
var xml = new ActiveXObject ("Microsoft.XMLDOM")
Xml.async = False
Xml.load ("Cd_catalog.xml")
Load the XSL
var xsl = new ActiveXObject ("Microsoft.XMLDOM")
Xsl.async = False
Xsl.load ("cd_catalog.xsl")
Transform
document.write (Xml.transformnode (XSL))
</script>
</body>
JavaScript is used in the code above, and if you don't know how to write JavaScript, you'd better learn it specifically.
The first code creates a Microsoft Parser (XMLDOM) Resolved object and reads the XML document into memory, the second code creates another object and imports the XSL document, and the last line of code converts the XML document into an XSL document and outputs the results to an HTML file.