Kurt Cagle

Subscribe to Kurt Cagle: eMailAlertsEmail Alerts
Get Kurt Cagle via: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn

Related Topics: RIA Developer's Journal, XML Magazine, AJAX World RIA Conference

RIA & Ajax: Article

Real-World AJAX Book Preview: Parsing and Serialization XML

Real-World AJAX Book Preview: Parsing and Serialization XML

This content is reprinted from Real-World AJAX: Secrets of the Masters published by SYS-CON Books. To order the entire book now along with companion DVDs for the special pre-order price, click here for more information. Aimed at everyone from enterprise developers to self-taught scripters, Real-World AJAX: Secrets of the Masters is the perfect book for anyone who wants to start developing AJAX applications.

Parsing and Serializing XML
Parsing and serialization were touched on briefly in the discussion of innerHTML, but both issues deserve more extensive coverage. A significant amount of work with AJAX-based systems involves converting strings of XML text into some form of DOM representation, a process formally known as XML parsing, or the reverse process of converting the DOM representation back to text, known formally as XML serialization.

Playing with Parsing
Currently there are two distinct methods for handling direct parsing and serialization. In the first (the W3C method), parsing is handled via the DOMParser() method. For AJAX purposes, the only relevant method, is the parseFromString() method that takes two arguments: the XML string representation and a mime type that attempts to interpret the result as HTML, XML, or XHTML (that should almost invariably be set to "text/xml" even when dealing with potential HTML output):

var parser = new DOMParser();
divText = "<div>This is a <span id='test'>test</span.</div>";
var xmlDom = parser.parseFromString(divText,"text/xml");

Note that the result is a fully formed document, not just an element. Typically, if you're trying to insert XML string content into an existing document, you should retrieve the documentElement of any such DOM that's created, then do a cloneNode(true) on this object to pass an element into the DOM tree.

For instance, one problem that occasionally occurs with non-HTML DOM elements is the fact that they don't support the innerHTML setter/getter property. You can create a setter that will let you assign an XHTML fragment even to a non-XHTML node, which I call the innerXHTML setter:

var e = Element.prototype;
      var currentElt = this;
      var parser = new DOMParser();
      xmlStr = "<span xmlns='http://www.w3.org/1999/xhtml'>"+xmlStr+"</span>";
      var xmlDom = parser.parseFromString(xmlStr,"text/xml");
      var newElt = xmlDom.documentElement.cloneNode(true);
      while (currentElt.firstChild != null){
      for (var index= 0;index != newElt.childNodes.length;index++){
         var node = newElt.childNodes.item(index);

Thus you could append to a non-HTML element as follows:

var nsComponents="http://www.metaphoricalWeb.com/xmlns/components";
var foo = document.createElementNS(nsComponents,"foo");
foo.innerXHTML = ‘<h1 style="color:green;">This is a test</h1>';

This will put a green <h1> tag with the content "This is a test" at the very end of the document. Admittedly, this is a very simplified example. As you start dealing with more elements that don't fit cleanly in the XHTML namespace (such as the clock), it may prove more beneficial over time, especially when the text in question comes from an AJAX XMLHttpRequest call.

Note that the DOM parser only works with XML documents – not HTML ones. Additionally, if the parse fails, the DOMParser object won't raise an exception. Instead, it will create an error "document" along the lines of:

<parsererror xmlns="http://www.mozilla.org/newlayout/xml/parsererror.xml">XML
Parsing Error: mismatched tag. Expected: </meta>. Location: chrome://extensiondev/
content/shell.html Line Number 59, Column 3:<sourcetext></head>

Internet Explorer, as previously mentioned, doesn't support the DOMParser. Instead, each document has an associated LoadXML() method that can be used to convert a string (or a DOM instance) into another DOM instance. To ensure serial processing of the script, you should set the async property of the document to false, otherwise, even loading from a string will trip it into an asynchronous operation:

var dom = new ActiveXObject("MSXML.DOMDocument");
dom.async = false;

Creating a (single method) DOMParser() object as a wrapper for IE is fairly trivial and is left as an exercise for the reader.

This content is reprinted from Real-World AJAX: Secrets of the Masters published by SYS-CON Books. To order the entire book now along with companion DVDs, click here to order.

More Stories By Kurt Cagle

Kurt Cagle is a developer and author, with nearly 20 books to his name and several dozen articles. He writes about Web technologies, open source, Java, and .NET programming issues. He has also worked with Microsoft and others to develop white papers on these technologies. He is the owner of Cagle Communications and a co-author of Real-World AJAX: Secrets of the Masters (SYS-CON books, 2006).

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.