Tuesday, 7 June 2011

XSLT Through JavaScript


cdcatalog.xml
<?xml version="1.0" encoding="ISO-8859-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>
.
.
</catalog>

cdcatalog.xsl
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
  <h2>My CD Collection</h2>
  <table border="1">
    <tr bgcolor="#9acd32">
      <th align="left">Title</th>
      <th align="left">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>

HTML Page
Here is the source code needed to transform the XML file to XHTML on the client:
<html>
<head>
<script>

function loadXMLDoc(fileName) {
    var xhttp;

    try {
        if (window.XMLHttpRequest) {
            xhttp = new XMLHttpRequest();
        }
        else {
            xhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xhttp.open("GET", fileName, false);
        xhttp.send("");
    }
    catch (err) { }

    return xhttp.responseXML;
}




function displayResult() {

    var xml;
    var xsl;
    var xsltProcessor;
    var resultDocument;

    try {
        xml = loadXMLDoc("cdcatalog.xml");
        xsl = loadXMLDoc("cdcatalog.xsl");
        // code for IE
        if (window.ActiveXObject) {
            ex = xml.transformNode(xsl);
            document.getElementById("DivExample").innerHTML = ex;
        }
        // code for Mozilla, Firefox, Opera, etc.
        else if (document.implementation && document.implementation.createDocument) {
            xsltProcessor = new XSLTProcessor();
            xsltProcessor.importStylesheet(xsl);
            resultDocument = xsltProcessor.transformToFragment(xml, document);
            document.getElementById("DivExample").appendChild(resultDocument);
        }
    }
    catch (err) { }
}
</script>
</head>
<body onload="displayResult()">
<div id="DivExample" />
</body>
</html>

No comments:

Post a Comment