Home arrow JavaScript arrow Page 3 - Manipulating XML Data with JavaScript
JAVASCRIPT

Manipulating XML Data with JavaScript


Yesterday you saw a number of different ways to obtain XML documents to manipulate with JavaScript. Today, you will learn how to manipulate the data. This article is excerpted from chapter 21 of JavaScript: The Definitive Guide, Fifth Edition, written by David Flanagan (O'Reilly; ISBN: 0596101996). Copyright © 2006 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

Author Info:
By: O'Reilly Media
Rating: 4 stars4 stars4 stars4 stars4 stars / 10
August 09, 2007
TABLE OF CONTENTS:
  1. · Manipulating XML Data with JavaScript
  2. · 21.2.2 Example: Creating an HTML Table from XML Data
  3. · 21.3 Transforming XML with XSLT
  4. · 21.4 Querying XML with XPath
  5. · 21.4.2 Evaluating XPath Expressions

print this article
SEARCH DEVARTICLES

TOOLS YOU CAN USE

advertisement
Manipulating XML Data with JavaScript - 21.3 Transforming XML with XSLT
(Page 3 of 5 )

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

<?xml version="1.0"?><!-- this is an xml document -->
<!-- declare the xsl namespace to distinguish xsl tags from html tags --> <xsl:stylesheet version="1.0"
               xmlns:xsl="http://www.w3.org/ 1999/XSL/Transform">
  <xsl:output method="html"/>

  <!-- When we see the root element, output the HTML framework of a table -->
  <xsl:template match="/">
   
<table>
      <tr><th>Name</th><th>E-mail Address</th></tr>
      <xsl:apply-templates/> <!-- and recurse for other templates -->
   
</table>
  </xsl:template>

  <!-- When we see a <contact> element...
-->
  <xsl:template match="contact">
    <tr> <!-- Begin a new row of the table
-->
      <!-- Use the name attribute of the contact as the first column -->
      <td><xsl:value-of select="@name"/>
      <xsl:apply-templates/> <!-- and recurse for other templates -->
    </tr>
  </xsl:template>

  <!-- When we see an <email> element, output its content in another cell -->
  <xsl:template match="email">
    <td><xsl:value-of select="."/></td> 
  </xsl:template>
</xsl:stylesheet>

XSLT transforms the content of an XML document using the rules in an XSL stylesheet. In the context of client-side JavaScript, this is usually done to transform the XML document into HTML. Many web application architectures use XSLT on the server side, but Mozilla-based browsers and IE support XSLT on the client side, and pushing the transform off the server and onto the client can save server resources and network bandwidth (because XML data is usually more compact than the HTML presentation of that data).

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:

  <?xml-stylesheet href="dataToTable.xml" type="text/xsl"?>

Note that the browser performs this kind of XSLT transformation automatically when an XML document containing an appropriate processing instruction is loaded into the browser display window. This is important and useful, but it is not the sub ject matter of this section. What I explain here is how to use JavaScript to dynamically perform XSL transformations.

The W3C has not defined a standard API for performing XSL transformations on DOM Document and Element objects. In Mozilla-based browsers, the XSLTProcessor object provides a JavaScript XSLT API. And in IE, XML Document and Element objects have a transformNode() 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

/**
 
* This XML.Transformer class encapsulates an XSL stylesheet.
 
* If the stylesheet parameter is a URL, we load it.
 * Otherwise, we assume it is an appropriate DOM Document.
 * /
XML.Transformer = function(stylesheet) {
    // Load the stylesheet if necessary.
    if (typeof stylesheet == "string") stylesheet = XML.load(stylesheet);
    this.stylesheet = stylesheet;

    // In Mozilla-based browsers, create an XSLTProcessor object and
    // tell it about the stylesheet.
    if (typeof XSLTProcessor != "undefined") {
        this.processor = new XSLTProcessor();
        this.processor.importStylesheet(this.stylesheet);
    }
};

/**
 
* This is the transform() method of the XML.Transformer class.
 
* It transforms the specified xml node using the encapsulated stylesheet.
 
* The results of the transformation are assumed to be HTML and are used to
 
* replace the content of the specified element.
 */
XML.Transformer.prototype.transform = function(node, element) {
    // If element is specified by id, look it up.
    if (typeof element == "string") element = document.getElementById(element);

    if (this.processor) {
        // If we've created an XSLTProcessor (i.e., we're in Mozilla) use it.
        // Transform the node into a DOM DocumentFragment.
        var fragment = this.processor.transformToFragment(node, document);
        // Erase the existing content of element.
        element.innerHTML = "";
        // And insert the transformed nodes.
        element.appendChild(fragment);
   
}
   
else if ("transformNode" in node) {
        // If the node has a transformNode() function (in IE), use that.
        // Note that transformNode() returns a string.
        element.innerHTML = node.transformNode(this.stylesheet);
   
}
   
else {
        // Otherwise, we're out of luck.
        throw "XSLT is not supported in this browser";
   
}
};

/**
 
* This is an XSLT utility function that is useful when a stylesheet is
 
* used only once.
 */
XML.transform = function(xmldoc, stylesheet, element) {
    var transformer = new XML.Transformer(stylesheet);
    transformer.transform(xmldoc, element);
}

At the time of this writing, IE and Mozilla-based browsers are the only major ones that provide a JavaScript API to XSLT. If support for other browsers is important to you, you might be interested in the AJAXSLT open-source JavaScript XSLT implementa tion. AJAXSLT originated at Google and is under development at http://goog-ajaxslt.sourceforge.net.


blog comments powered by Disqus
JAVASCRIPT ARTICLES

- More Top jQuery Tutorials for Beginners
- More Top jQuery Plugins for Menus
- Top jQuery Tutorials for Beginners
- New UI Framework and SDK for JavaScript Rele...
- JavaScript OpenPGP Tool, Node.js 0.6.3 Avail...
- Yahoo Releases Cocktails Language and Develo...
- Customizing jQuery Slideshows: Dynamic Contr...
- Customizing jQuery Slideshows: the animate()...
- Customizing jQuery Slideshows: slideUp() and...
- Customizing jQuery Slideshows: hide() and sh...
- Web Workers: Performing Calculations in Para...
- More Top JavaScript Frameworks and Libraries
- More Dynamic jQuery Styling Techniques
- The Top JavaScript Libraries
- The Top JavaScript Frameworks

Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 



© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 2 - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials