10.6. Client-Side Transformations
When setting out to perform client-side transformations, the first tasks are always to obtain the XML and the XSL style sheet. A number of ways exist for doing this, ranging from having the document embedded in the web page, to loading it directly from the web server, to requesting it from a web service. How the document is obtained isn't nearly as important as just obtaining it. The next task it to create an XSLT processor, pass the style sheet and the XML document, and then get the resulting document and use it. This whole process sounds relatively easy, doesn't it? And my question is loaded, isn't it? The answers to the questions are "yes" and "no." Applying an XSL style sheet in the browser is actually as easy as it sounds.
With client-side transformations, the only "gotcha" is being aware of the browser. ActiveX won't work in Firefox, Flock, Mozilla, or Netscape, and nothing but ActiveX will work in Internet Explorer. Yes, it is an annoyance, but it is nothing that we haven't lived with for the better part of a decade. Besides, this is one of those things that, once coded, can be cloned again and again. In short, it is a nice addition to our bag of tricks.
10.6.1. XSLT in Microsoft Internet Explorer
var XSLTemplate = new ActiveXObject('MSXML2.XSLTemplate.3.0');
XSLTemplate.stylesheet = XSL;
The next step is to create an XSLT processor using the instance of the XSL template:
var XSLTProcessor = XSLTemplate.createProcessor;
Now it is time to specify the XML document to the XSLT processor in the following manner:
XSLTProcessor.input = XML;
Hang in there; the end is in sight. So far, we've created an XSL template, specified the XSL style sheet, created an XSLT processor, and specified the XML document. This leaves just two steps, the first of which is applying the style sheet:
The final step is simply to use the output from the processor, which, incidentally, is text:
document.getElementById('example').innerHTML = XSLTProcessor.output;
Listing 10-14. Internet Explorer
If you're a big fan of complicated procedures, such as the one necessary with Microsoft Internet Explorer shown earlier, be ready to be disappointed. Unlike Internet Explorer, the other browsers that support XSLT, including open source browsers such as Firefox, Mozilla, and Flock, require a simple three-step process:
The only oddities, from an Internet Explorer point of view, are the fact that the result is an XML document or document fragment. This means that there are two methods for applying an XSL style sheet: one for documents, transformToDocument, and a second for document fragments, transformToFragment. Listing 10-15 shows how it works using the transformToFragment method.
Listing 10-15. Non-IE
In my opinion, unless the application is an intranet application, the way to go is to code to use both types of browsers. But that is a personal decision; just remember that sometimes an intranet application doesn't stay an intranet application.