04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 15: XML in JavaScript<br />

These methods aren ’ t used often and are provided mostly for convenience.<br />

Resetting the Processor<br />

Each XSLTProcessor instance can be reused multiple times for multiple transformations with different<br />

XSLT style sheets. The reset() method removes all parameters and style sheets from the processor,<br />

allowing you to once again call importStylesheet() to load a different XSLT style sheet as in this example:<br />

var processor = new XSLTProcessor()<br />

processor.importStylesheet(xsltdom);<br />

//do some transformations<br />

processor.reset();<br />

processor.importStylesheet(xsltdom2);<br />

//do more transformations<br />

Reusing a single XSLTProcessor saves memory when using multiple style sheets to perform<br />

transformations.<br />

Cross - Browser XSLT<br />

The IE-to-XSLT transformation is quite different from the XSLTProcessor approach, so recreating all of<br />

the functionality available in each is not realistic. The easiest cross - browser technique for XSLT<br />

transformations is to return a string result. For IE, this means simply calling transformNode() on the<br />

context node, whereas other browsers need to serialize the result of a transformToDocument()<br />

operation. The following function can be used in IE, Firefox, Chrome, Safari, and Opera:<br />

function transform(context, xslt){<br />

if (typeof XSLTProcessor != “undefined”){<br />

var processor = new XSLTProcessor();<br />

processor.importStylesheet(xslt);<br />

var result = processor.transformToDocument(context);<br />

return (new XMLSerializer()).serializeToString(result);<br />

}<br />

} else if (typeof context.transformNode != “undefined”) {<br />

return context.transformNode(xslt);<br />

} else {<br />

throw new Error(“No XSLT processor available.”);<br />

}<br />

The transform() function accepts two arguments: the context node on which to perform the<br />

transformation and the XSLT document object. First, the code checks to see if the XSLTProcessor type is<br />

defined and if so, it uses that to process the transformation. The transformToDocument() method is<br />

called and the result is serialized into a string to be returned. If the context node has a transformNode()<br />

method, then that is used to return the result. As with the other cross - browser functions in this chapter,<br />

transform() throws an error if there is no XSLT processor available. This function is used as follows:<br />

var result = transform(xmldom, xsltdom);<br />

545

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!