JavaScript and XML : Page 2 | JavaScript: The Definitive Guide, Fifth Edition | WebReference

JavaScript and XML : Page 2 | JavaScript: The Definitive Guide, Fifth Edition

[previous] [next]

JavaScript and XML

21.1.2 Loading a Document from the Network

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 techniques 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

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

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

[previous] [next]