JS Transformer

- 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.
NOTE:
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:
- Get an XML file you want to parse (for example, the Yahoo! Entertainment news feed)*
- Find or write your own XSL to transform the format of the XML chosen (for example, the XSL from Make RSS Pretty)
- 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?
-OR-
view the full text on Snipplr
Summary
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 and W3Schools).
Related articles
- XSLTJSON, XML to JSON using XSLT – bramstein.com (bramstein.com)
- GRDDL Use Cases: Scenarios of extracting RDF data from XML documents (w3.org)
- Integrate disparate data sources with Semantic Web technology (ibm.com)

Leave a Reply
No trackbacks yet.
No post with similar tags yet.
Posts in similar categories
BC$ = Behavior, Content, Money
The goal of the BC$ project is to raise awareness and make changes with respect to the three pillars of information freedom - Behavior (pursuit of interests and passions), Content (sharing/exchanging ideas in various formats), Money (fairness and accessibility) - bringing to light the fact that:
1. We regularly hand over our browser histories, search histories and daily online activities to companies that want our money, or, to benefit from our use of their services with lucrative ad deals or sales of personal information.
2. We create and/or consume interesting content on their services, but we aren't adequately rewarded for our creative efforts or loyalty.
3. We pay money to be connected online (and possibly also over mobile), yet we lose both time and money by allowing companies to market to us with unsolicited advertisements, irrelevant product offers and unfairly structured service pricing plans.
One of the best Web Design guides out there is still CSS Zen Garden. Not only does it prov...
An early Christmas present or homework for the holidays?
A yay or nay from world-renown...
With the real, true and unbiased news inevitably moving online towards the so-called "Alternative Media" (which really is almost reaching the point where it is not alternative so much as the first go-to source), its a good idea to start replicating some of the most useful elements from Television, Print and Radio (aka. the rest...
Since the February confirmation of the Facebook IPO, Facebook has continued to stagnate in user-base yet as an organization it holds no punches as it attempts to grow internationally, and its stock price continues to soar as Class A shares finally open up to the average person (major investment firms had first dibs at the...
The Royal Canadian Mint(RCM) has sponsored the MintChip Challenge 2012 in an effort to attract developers to the idea of developing software for the MintChip and giving away their best financial application ideas, basically, for free (on the long-shot that you are one of the few who win).
Starting April 1st, 2012, they began mailing out...
Popcorn.js is an incredibly useful framework for adding timing-based events and/to Semantic metadata to rich content.
According to Mozilla: "Popcorn makes video work like the web. We create tools and programs to help developers and authors create interactive pages that supplement video and audio with rich web content, allowing your creations to live and grow online."
With...
Social media has taken over the web (for now) and the name of the game is sharing, something legislation like SOPA and PIPA just didn't seem to understand. Rather than figuring out a new economic model based on the reality of sharing on the web, that rewards this type of activity (which is essentially just...
iScroll 4 is the latest version and release of an excellent content slider-type JavaScript component by Matteo Spinelli. While one may argue that content sliders are a dime a dozen, iScroll differs in the fact that it has full support for all the main WebKit for iOS gestures including pinch/zoom, pull-up/pull-down, smooth scrolling and screen...
Well, I've decided to give this one away in the title, since the good folks over at ChalkGaming helped me out quite a bit while consulting with a big client who wanted to integrate Sports Stats into their Online Newspaper properties.
Requirement
Create a sports widget to display quality sports data (including: schedules, box scores, standings, betting...
For a long time now, I've been a paying customer of SchedulesDirect, and by that token their parent company Zap2it (now a Tribune Media Services company).
Recently, I've started publishing my own personal Electronic Programming Guide (EPG) here on BCmoney MobileTV in an accessible format:
BC$ EPG
One of the secondary goals of my MobileTV project has...
Long before the release of the W3C's Widget specification, most modern programming languages had already (predictably) evolved a system for plugins, extensions and/or the representation of widgets.
I've accepted a new position at TeamSpace / TheREDspace in Halifax, NS; and, while I'm not at liberty to divulge much juicy information about my clients or their technologies,...
Yesterday I wrote about the Google API shutdown. It seems that I was wrong in that post about Wordreference not having an API, just a few days earlier founder Michael Kellogg announced the introduction of the brand-spanking new Wordreference API.
Like a dunce I contacted Michael by email to learn about this new revelation without double-checking...