Behavior, Content, Money – 3 Things you should never give away for free!!!

BCmoney MobileTV

JS Transformer

Posted by bryan on December 8, 2010 in AJAX, HTML, JavaScript, XML with No Comments

No Gravatar
Megan Fox and Shia Labeouf promoting Transform...
Image via Wikipedia

The official release of one of the most useful (yet hackish, and randomly pieced together from the interweb) code snippets I’ve ever made. I’m calling this useful little piece of code “JS Transformer”, since Transformers are cool again thanks to Shia LaBeouf.

KEEP IN MIND THE SAME-ORIGIN POLICY OF MOST BROWSERS… you’ll probably have to use a server-side proxy to make this more useful (i.e. proxy.php, proxy.jsp, proxy.asp, etc… a topic I’ve covered before)

Who made it?

Me, Bryan Copeland, with the help of several online resources, in particular W3schools’ section on the XML DOM, Mozilla foundation’s excellent tutorial on XSL Transformations and Netlobo’s infamous article on getting URL parameters in Javascript.

What is it?

A simple single-file example using the power of thin-clients to display data dynamically, using JavaScript, HTML, XML, the browser’s internal XSL Processor, and (optionally) CSS for a dash of your own presentation/design.

What does it do?

Allows you to make an AJAX request to an XML data source, perform XML parsing, and all without breaking too much of a sweat.

Why use it?

It’s perfect for rapid prototyping with XML and/or XSL Transformations… for example, I’ve recently used it for combining SportsML data from xmlteam with SportsMLT (DEMO here), and for building a simple client-side parser based on XSL, which could then be applied to render XML medical application data & vital signs in multiple programming languages (since every language from C to XML itself has a way to apply stylesheets), something which was very useful for a project which had a constantly changing XML schema, and for which rewriting many parsers would quickly become a nightmare!

How does it work?

First, you need to grab the URL parameters if you want to use anything other than the hard-coded XML and XSL files:

x = gup("xml");
var xmlFile = (typeof x != "undefined" && x !== null && x != "") ? x : "data.xml";
s = gup("xsl");
var xslFile = (typeof s != "undefined" && s !== null && s != "") ? s : "data2html.xsl";

We use a helper function gup, which I won’t explain here, suffice to say that it stands for Get URL Parameters, and it does just that, looks for any additional parameters tacked on to the URL after a “?” and enables their values to be mapped to a JavaScript variable. If we can’t find any URL parameters, we fallback to some hard-coded example data. Depending on your intended usage and needs, the hard-coded option may in fact be all you need, in which case you can just strip out the URL Parameter handling code.

Next, we display the result of the transformation:

function displayResult()
	xml=loadXMLDoc(xmlFile); //load the XML file using AJAX
	xsl=loadXMLDoc(xslFile); //load the XSL file using AJAX

       //browser-specific XSL Transformation code follows
	if (window.ActiveXObject)	// IE
	  ex = xml.transformNode(xsl); //transform XML nodes using XSL templates
	  document.getElementById("result").innerHTML = ex; //apply "parsed" result to our placeholder div
	else if (document.implementation && document.implementation.createDocument) // Mozilla, Firefox, Opera, Chrome, Safari, etc.
	  xsltProcessor=new XSLTProcessor(); //initialize browser's XSLT
	  xsltProcessor.importStylesheet(xsl); //load XSL file into processor
          //next, load the XML and make a call to transform it
	  resultDocument = xsltProcessor.transformToFragment(xml,document);
	  document.getElementById("result").appendChild(resultDocument); //apply "parsed" result to our placeholder div

The important thing to note here, is that we rely on the Browser’s internal XSL Transformation Processor. XSLT has been around for a long time and by now “most” browsers have gotten their implementations aligned. With the IE check taken into account, it should be fairly reliable but do keep an eye out for cross-browser variations just in case. I’ve tested in the major browsers to date with success so far (IE 7/8/9, FF 3.6+, Opera 10+, Safari 5+, Chrome 8+). Let me know in the comments if you run into a browser version with bugs or where this technique fails completely.

Steps to test it yourself:

  1. Get an XML file you want to parse (for example, the Yahoo! Entertainment news feed)*
  2. Find or write your own XSL to transform the format of the XML chosen (for example, the RSS to HTML converter XSL, originally from the Making RSS Pretty post)
  3. Just feed as URL parameters, both an XML file (RDF, RSS, Atom, or any other XML-family format would work too) and corresponding XSL file to process it

* (see note above about same-origin limitations of most browsers, it is advisable to download the content statically to your server or else you’ll likely need to create a proxy as was done in the example widget…)


Where can I get it?

view the full text on Snipplr



Anyway, its just a useful little tool… but surely this is an anti-pattern of some sort and someone will find a way to criticize it, or consider it an example of what not to do, but hey, I love it and use it regularly.

Hope someone else will too, and be sure to give credit where credit is due (no, not to me… mostly Netlobo, Sean M. Burke and W3Schools).