Example: Use XSLT transformation in browser

Several readers were asking for an code sample that performs XSLT transformation in the browser, so here it is :) To start with, you should use a wrapper library to isolate yourself from browser version/platform inconsistencies. I'm using Sarissa to deal with XML, XSLT and HttpRequest and X library to deal with DHTML-related functions.

The most common XSLT-related operation that you do in your browser is this:

  • Download XML document from the web server using XMLHttpRequest;
  • Transform the XML into application-specific HTML markup with an XSLT transformation;
  • Insert the resulting HTML markup into the web page.

Sarissa library has a function (Sarissa.updateContentFromURI) that does almost exactly what you need to get there, so you only need to perform the following steps:

  • Load the XSLT stylesheet as XML document (sync load is easier to do).
  • Import the loaded XML document into an XSL processor (special object that can perform the XSLT transformations).
  • Call the updateContentFromURI function.

The resulting code is very simple:

// load XSLT stylesheet, done only once.
var xsl = loadURI("moveRoutes_lists.xsl");
if (!xsl) throw("Cannot load XSL stylesheet");

var xform = new XSLTProcessor();
xform.importStylesheet(xsl);

// the following call transforms a remote XML document
// into HTML fragment and inserts it into the target
// element
Sarissa.updateContentFromURI(remoteURI, xGetElementById(targetElement),xform);

Notes:

  • sarissa.js as well as sarissa_dhtml.js libraries have to be included in the source document.
  • xGetElementById function is part of the X library.
  • loadURI function is documented here.

No comments:

Post a Comment