Home arrow JavaScript arrow Page 3 - JavaScript and XML

JavaScript and XML

If you want to learn how to use JavaScript to work with XML data, you've come to the right place. This three-part article series starts by showing you how to obtain XML documents. It 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 / 84
August 08, 2007
  1. · JavaScript and XML
  2. · 21.1.1 Creating a New Document
  3. · 21.1.2 Loading a Document from the Network
  4. · 21.1.4 XML Documents from Data Islands

print this article

JavaScript and XML - 21.1.2 Loading a Document from the Network
(Page 3 of 4 )

Chapter 20 showed how to use the XMLHttpRequest object to dynamically issue HTTP requests for text-based documents. When used with XML documents, the responseXML property refers to the parsed representation as a DOM Document object. XMLHttpRequest is nonstandard but widely available and well understood, and is usually the best technique for loading XML documents.

There is another way, however. An XML Document object created using the tech niques shown in Example 21-1 can load and parse an XML document using a less well-known technique. Example 21-2 shows how it is done. Amazingly, the code is the same in both Mozilla-based browsers and in IE.

Example 21-2. Loading an XML document synchronously

* Synchronously load the XML document at the specified URL and
* return it as a Document object
 * /
XML.load = function(url) {
    // Create a new document with the previously defined function
    var xmldoc = XML.newDocument();
    xmldoc.async = false;  // We want to load synchronously
    xmldoc.load(url);      // Load and parse
    return xmldoc;         // Return the document

Like XMLHttpRequest, this load() method is nonstandard. It differs from XMLHttpRequest in several important ways. First, it works only with XML documents; XMLHttpRequest can be used to download any kind of text document. Second, it is not restricted to the HTTP protocol. In particular, it can be used to read files from the local filesystem, which is helpful during the testing and development phase of a web application. Third, when used with HTTP, it generates only GET requests and cannot be used to POST data to a web server.

Like XMLHttpRequest, the load() method can be used asynchronously. In fact, this is the default method of operation unless async property is set to false . Example 21-3 shows an asynchronous version of the XML.load() method.

Example 21-3. Loading an XML document asynchronously

* Asynchronously load and parse an XML document from the specified URL.
* When the document is ready, pass it to the specified callback function.
 * This function returns immediately with no return value.
XML.loadAsync = function(url, callback) {
    var xmldoc = XML.newDocument();

    // If we created the XML document using createDocument, use
    // onload to determine when it is loaded
    if (document.implementation && document.implementation.createDocument) {
        xmldoc.onload = function() { callback(xmldoc); };
    // Otherwise, use onreadystatechange as with XMLHttpRequest
    else {
xmldoc.onreadystatechange = function() {
            if (xmldoc.readyState == 4) callback(xmldoc);

    // Now go start the download and parsing

21.1.3  Parsing XML Text

Sometimes, instead of parsing an XML document loaded from the network, you simply want to parse an XML document from a JavaScript string. In Mozilla-based browsers, a DOMParser object is used; in IE, the loadXML() method of the Document object is used. (If you paid attention to the XML.newDocument() code in Example 21-1, you’ve already seen this method used once.)

Example 21-4 shows a cross-platform XML parsing function that works in Mozilla and IE. For platforms other than these two, it attempts to parse the text by loading it with an XMLHttpRequest from a data: URL.

Example 21-4. Parsing an XML document

* Parse the XML document contained in the string argument and return
 * a Document object that represents it.
XML.parse = function(text) {
if (typeof DOMParser != "undefined") {
        // Mozilla, Firefox, and related browsers
        return (new DOMParser()).parseFromString(text, "application/xml");
    else if (typeof ActiveXObject != "undefined") {
// Internet Explorer.
        var doc = XML.newDocument( );   // Create an empty document
        doc.loadXML(text);              //  Parse text into it
        return doc;                     // Return it
else {
        // As a last resort, try loading the document from a data: URL
// This is supposed to work in Safari. Thanks to Manos Batsis and
// his Sarissa library (sarissa.sourceforge.net) for this technique.
var url = "data:text/xml;charset=utf-8," + encodeURIComponent(text);
var request = new XMLHttpRequest();
request.open("GET", url, false);
return request.responseXML;

blog comments powered by Disqus

- Project Nashorn to Make Java, JavaScript Wor...
- JavaScript Virus Attacks Tumblr Blogs
- Google Releases Stable Dart Version, JavaScr...
- Khan Academy Unveils New JavaScript Learning...
- Accessing Nitro? There`s an App for That
- JQuery 2.0 Leaving Older IE Versions Behind
- Fastest JavaScript Engine Might Surprise You
- Microsoft Adjusting Chakra for IE 10
- Brendan Eich: We Don`t Need Google Native Cl...
- An Overview of JavaScript Statements
- An Overview of JavaScript Operators
- Overview of JavaScript Variables
- More of the Top jQuery Social Plugins
- The Top jQuery Social Plugins
- More of the Top jQuery Slider Plugins

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


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