Tuesday, November 8, 2011

Easy XSLT without installing anything


Sometimes you need to apply an XSLT to some XML, and there are (at least) a couple of ways to do it:

(a) Install a processor like Saxon and run it through the command line;
(b) Reference an XSLT from your XML file, and then open it in a browser;

Both are somewhat problematic - the first one requires installing and running something, and the second requires modifications to the XML. I propose a useful and effective alternative, which I've been using successfully for quite a while. The idea is as following: you simply open a special HTML in a browser. This HTML contains a JavaScript that loads both XML and XSLT files, applies the transform and renders the result into its own DOM. Here is the HTML I use, it is really simple and works in both IE and Mozilla. All you need to do is replace the filenames (input.xml and template.xsl):
<html>
<head>
<script>
function loadXMLDoc(fname)
{
var xmlDoc;
if (window.ActiveXObject)
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
}
else if (document.implementation && document.implementation.createDocument)
{
xmlDoc = document.implementation.createDocument("","",null);
}
else
{
alert('Your browser cannot handle this script');
}
xmlDoc.async = false;
xmlDoc.load(fname);
return(xmlDoc);
}

function displayResult()
{
xml = loadXMLDoc("input.xml");
xsl = loadXMLDoc("template.xsl");
if (window.ActiveXObject)
{
ex = xml.transformNode(xsl);
document.getElementById("content").innerHTML = ex;
}
else if (document.implementation && document.implementation.createDocument)
{
xsltProcessor=new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
resultDocument = xsltProcessor.transformToFragment(xml,document);
document.getElementById("content").appendChild(resultDocument);
}
}
</script>
</head>
<body onLoad="displayResult()">
<div id="content" />
</body>
</html>

A sample use case: you have an application which logs some data into an XML file at a given location. You write an XSLT that filters errors in this log, and adjust the filenames inside the HTML above. You save this HTML on your Desktop, and every time you open or refresh it, it shows you the current errors in the log. It is easier and more user-friendly than running BAT-files saving output of transform into some temporary HTML and then opening it.

No comments:

Post a Comment