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 ?
You have not misunderstood how XSLT works. The code is putting the html
and body
nodes within your div
element. It is just that the browser is probably choosing to ignore them at that point and not add them to the DOM.
So the example of W3Schools is probably very misleading. The XSLT should not really include the html
and body
tags. You would only really need them if you were using the <?xml-stylesheet
processing instruction in the XML, to display XML as HTML in the browser (as shown at http://www.w3schools.com/xsl/xsl_transformation.asp, for example)