Client XSL Transformations from Asp.Net Webservice Response

I wrote previously about how you can use jQuery to query Asp.Net WebServices. We are now going to build on that by using xslt to transform the xml returned from your web service and insert it in to your document.

Download the full script

We are going to need two further functions, the first to load your xslt file and the second to do the transform.

Remember not to crowd the root namespace so start by building upon our previous DT namespace:

DT.xml = {}

Then add the functions:


DT.xml.loadXMLDoc = function(fname) {
var xmlDoc;
// code for IE
if (window.ActiveXObject) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.load(fname);
return (xmlDoc);
}
// code for Mozilla, Firefox, Opera, etc.
else if (window.XMLHttpRequest) {
xmlDoc = new window.XMLHttpRequest();
xmlDoc.open("GET", fname, false);
xmlDoc.send("");
return xmlDoc.responseXML;
}
else {
alert('Your browser cannot handle this script');
}
}

DT.xml.xslTransform = function(xml, xsl) {
// code for IE
if (window.ActiveXObject) {
ex = xml.transformNode(xsl);
return ex;
}
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument) {
xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
resultDocument = xsltProcessor.transformToFragment(xml, document);
return resultDocument;
}
}

Now we can update the HelloWorld method to add the transformed html to the DOM. This needs to be run once the DOM has been loaded so you would either put this code within the jQuery ready event or a user inititiated event.


DT.wsCustom.HelloWorld(function(xData,textStatus){
xsl = DT.xml.loadXMLDoc("yourxsl.xslt");
doc = DT.xml.xslTransform(xData.responseXML,xsl);
$("#HelloWorldDiv").html(doc);
});

As you can see this is extremely simple but has the potential to completely revolutionise the way that you create web applications.

One response to this post.

  1. […] is just a quick start to using jQuery to access Asp.Net web services. Here is part 2 to include XSL transforms and more advanced web […]

    Reply

Leave a comment