Ajax and XSLT – Inline XML Transformations
Bowser based XSL transformations offer a handy and powerful way in integrating XML data to web applications. In combination with HTTP server requests, as introduced by Ajax, the data structures can be loaded and rendered in common HTML code. Reuse of the documents inreases and a server-side parsing and transformation becomes obsolete.
Current browsers have opend their APIs and offer access to their rendering and trandformation objects which can be used in client side Javascript code. One of these objects is the XSLTProcessor which allows XSL transformation done one the fly at any time during the users interaction with the webpage. The obvious advantage against hand-made XML parsing and creating a new HTML compatible structure is speed. As the XSLTProcessor object is compiled and a part of the Browser, it can do transformations really fast.
The following example shows how the object can easily be used within Javascript code on Mozilla. All the transfom method requires are two strings, one representing the XSL stylesheet and one holding the XML data. THis data is converted into a DOM object to work with. The method returns the transformed HTML code which can be integrated at any place in the document. The example code uses Prototype as Javascript framework.
Transformation.prototype = {
initialize: function(){
this.xslProc = undefined;
this.styleshees = undefined;
this.xmldata = undefined;
},
transform: function(stylesheet, xmldata){
// mozilla
if(document.implementation.createDocument) {
this.xslProc = new XSLTProcessor();
var parser = new DOMParser();
this.stylesheet = parser.parseFromString(stylesheet, "text/xml");
this.xslProc.importStylesheet(this.stylesheet);
this.xmldata = parser.parseFromString(xmldata, "text/xml");
var fragment = this.xslProc.transformToFragment(this.xmldata, document);
var tmpBox = document.createElement("div");
tmpBox.appendChild(fragment);
return tmpBox.innerHTML;
}
else {
// IE implementation not done yet ;)
}
}
}
The stylesheet and XML data are loaded via a HTTP request when the user demands the data.
Loader.prototype = {
initialize: function(o){
obj = o;
},
load: function(src, post, obj, callback){
var opt = {
method: 'post',
postBody: post,
onSuccess: function(data){ callback.call(obj, data.responseText);},
onFailure: this.onFailure
}
new Ajax.Request(src, opt);
},
onFailure: function(err){
alert('Error 404: file not found');
}
}
With the concept of inline XSL transformation, XSLT shows again how it can be used in modern web application development. Aside with Ajax, the duo forms a new promising methology for building and structuring websites.
Edit: More profound information on the topic can be found on ajaxpatterns.org, a resource on Ajax.
Check out the transformation example or download the sources: Ajax XSLT tranformation
Comments are closed.