JavaScript XSLT Support in Firefox

By Nicholas C. Zakas

Beginning in Firefox 1.0, a new object called XSLTProcessor has been available to JavaScript developers in order to enable client-side XSLT transformations. This object uses Firefox's built-in XSLT processor, Transformiix, to enable this functionality.

The first step in the transformation is to load both the XML and XSLT into DOMs:

oXmlDom.load("employees.xml");
oXslDom.load("employees.xslt");

Then, create the XSLTProcessor and use the importStylesheet() method to assign the XSLT DOM:

The last step is to call either transformToDocument() or transformToFragment() with the XML DOM as an argument to produce a result. As you may have guessed, transformToDocument() returns a new DOM document as its result and transformToFragment() returns a new document fragment as its result. Generally speaking, you should use transformToDocument() unless you intend to add the result directly to an existing document; then you should use transformToFragment().

When using transformToDocument(), just pass in the XML DOM and use the result as another completely different DOM:

In the previous example, the processor creates a fragment owned by the document object. This enables the fragment to be added to a <div/> element existing in the page.

This all makes perfect sense when the output method for XSLT is either HTML or XML, but what about when the output is text? To solve this problem, Firefox creates an XML document with a single element, <transformiix:result/>, that contains all the text output. So, using text output from an XSLT file still results in a valid document or document fragment.

Keeping this in mind, it's possible to create a version of IE's transformNode() method for Firefox. This can be done by adding a method to the Node object's prototype:

This method creates a result document using the given XSLT DOM. The resulting XML code is then stored in sResult using the xml property defined earlier in the chapter. That code is then checked to see if it contains <transformiix:result/>. If it does, then the XML part is stripped out (by taking only the string between the first greater-than symbol and the last less-than symbol). Lastly, sResult is returned. Using this method, you can create code to run in both Firefox and IE:

The XSLTProcessor in Firefox also allows you to set XSLT parameters. The setParameter() method accepts three arguments: the namespace URI, the parameter local name, and the value to set. Typically, the namespace URI is null and the local name is simply the parameter's name. This method must be called prior to transformToDocument() or transformToFragment():

Two other methods are related to parameters, getParameter() and removeParameter(), which are used to get the current value of a parameter and remove the parameter value, respectively. Each method takes the namespace URI (once again, typically null) and the local name of the parameter: