18 - Client-side XSL transformations with JavaScript
(Microsoft Internet Explorer only)


On page 2 we saw the easiest way to do a client-side XSL transformation using the XSL transformation engine built into Microsoft Internet Explorer. The transformation was done by simply including the line:

<?xml-stylesheet type="text/xsl" href="iliad.xsl"?>

into the XML file itself, thus specifying which XSL stylesheet to use (in this case iliad.xsl).

However, one may wish to perform more complex operations that require collecting input from the user using a regular HTML form with input boxes, check boxes, drop-down menus, etc. In this case it is necessary to use JavaScript to collect the information from the form, pass the information to the XSL file, and complete the transformation.

In the following example, the user can enter a name (e.g. "Achilles" or "Zeus") and the XSL stylesheet (using xsl:if and the contains() function--see pages 5 and 8) will return any line of the poem in which that name is found. Click here to try it out.

JavaScript and HTML Code
(explanatory notes are in red)
<script language="JavaScript">

function transform(query) {
xml = "iliad18.xml";
xsl = "iliad18.xsl";

// Load the XML Document
var xmlDoc = new ActiveXObject("Msxml2.DOMDocument");
xmlDoc.async = false;
xmlDoc.resolveExternals = false;
xmlDoc.load(xml);

// Load the XSL file
var xslt = new ActiveXObject("Msxml2.XSLTemplate");
var xslDoc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument");
xslDoc.async = false;
xslDoc.load(xsl);
xslt.stylesheet = xslDoc;

// Create the XSLT Processor
var xslProc;
xslProc = xslt.createProcessor();
xslProc.input = xmlDoc;

// Pass Variables to the XSL file
xslProc.addParameter("query", query);

// Perform the Transformation
xslProc.transform(); 

// Write the output to the HTML Table cell named "output"
document.getElementById('output').innerHTML = xslProc.output;
}
</script>


<html>
<head>
<style tpe="text/css">
	.menu {text-align:left; vertical-align:top; background:lightblue; border-style:double;}
	.outputcell (text-align:left; background:#FFFFFF;}
</style>
</head>
<body bgcolor="#FFFFFF">

<form id="myform">
<table cellpadding="5" cellspacing="0" border="0" width="100%">
<tr>
<td class="menu">
	Find the name: <input type="text" id="query"><input type="button" value="Submit" onClick="transform(myform.query.value);">
</td>
</tr><tr>
<td class="outputcell" id="output" colspan="4"> </td>
</tr>
</table>
</form>

</body>
</html>
This code will generate a web page that looks like this:


The page consists of one HTML Table that has one column and two rows. The upper row (in lightblue) is the "menu" where the user can enter data. The lower row (invisible until the transformation is performed) is the "output" area where the results appear.