21.3 Transforming XML with XSLT
Once you've loaded, parsed, or otherwise obtained a Document object representing an XML document, one of the most powerful things you can do with it is transform it using an XSLT stylesheet. XSLT stands for XSL Transformations, and XSL stands for Extensible Stylesheet Language. XSL stylesheets are XML documents and can be loaded and parsed in the same way that any XML document can. A tutorial on XSL is well beyond the scope of this book, but Example 21-8 shows a sample stylesheet that can transform an XML document like the one shown in Example 21-6 into an HTML table.
Example 21-8. A simple XSL stylesheet
Many modern browsers can style XML using either CSS or XSL stylesheets. If you specify a stylesheet in an xml-stylesheet processing instruction, you can load an XML document directly into the browser, and the browser styles and displays it. The requisite processing instruction might look like this:
The W3C has not defined a standard API for performing XSL transformations on DOM Document and Element objects. In Mozilla-based browsers, the
atransformNode() method for performing transformations. Example 21-9 shows both APIs. It defines an XML.Transformer class that encapsulates an XSL stylesheet and allows it to be used to transform more than one XML document. The
transform() method of an
XML.Transformer object uses the encapsulated stylesheet to transform a specified XML document and then replaces the content of a specified DOM element with the results of the transformation.
Example 21-9. XSLT in Mozilla and Internet Explorer