I am following this tutorial: http://www.w3schools.com/xsl/xsl_client.asp
I have an HTML page. I want to create the HTML using data from an XML file, and style it using XSLT, by using JavaScript to read the XML and XSLT files from the server.
HTML page:
<html>
<head>
<script type="text/javascript" src="/scripts/onload.js"></script>
</head>
<body onload="displayResult()">
<div id="example" />
</body>
</html>
Javascript:
function loadXMLDoc(filename)
{
if (window.ActiveXObject)
{
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
else
{
xhttp = new XMLHttpRequest();
}
xhttp.open("GET", filename, false);
try {xhttp.responseType = "msxml-document"} catch(err) {} // Helping IE11
xhttp.send("");
return xhttp.responseXML;
}
function displayResult()
{
var location = document.URL;
var xmlLocation = location +"myXMl.xml";
xml = loadXMLDoc(xmlLocation);
xsl = loadXMLDoc("style.xsl");
// code for IE
if (window.ActiveXObject || xhttp.responseType == "msxml-document")
{
ex = xml.transformNode(xsl);
document.getElementById("example").innerHTML = ex;
}
// code for Chrome, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument)
{
xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
resultDocument = xsltProcessor.transformToFragment(xml, document);
document.getElementById("example").appendChild(resultDocument);
}
}
XSLT file:
<?xml version="1.0" encoding="UTF-8"?>
<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>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="movie">
<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>
The xml file is nothing special - as it just contains the CD's info etc.
I am confused because it looks like I am "inserting" the output of the XSLT into the "example" div
which is already in the body
of the html
. But the XSLT already defines a html
, head
and body
nodes. So aren't I technically putting an <html>
node inside the <div id="example" />
, and shouldn't that lead to incorrect html ? (nested html
tags) ? When I look at the console in safari, the DOM looks normal (there is only one set of html
, head
, body
etc. So what is going on ? Have I misunderstood how XSLT works ?