Welcome!

Machine Learning Authors: Zakia Bouachraoui, Liz McMillan, Roger Strukhoff, Pat Romanski, Carmen Gonzalez

Related Topics: Machine Learning

Machine Learning : 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;
e.__defineSetter__("innerXHTML",function(xmlStr){
      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){
         currentElt.removeChild(currentElt.firstChild);
         }
      for (var index= 0;index != newElt.childNodes.length;index++){
         var node = newElt.childNodes.item(index);
         currentElt.appendChild(node.cloneNode(true));
         }
      });

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");
document.body.appendChild(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>
--^</sourcetext></parsererror>

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;
dom.loadXML("<root/>");

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.


CloudEXPO Stories
The precious oil is extracted from the seeds of prickly pear cactus plant. After taking out the seeds from the fruits, they are adequately dried and then cold pressed to obtain the oil. Indeed, the prickly seed oil is quite expensive. Well, that is understandable when you consider the fact that the seeds are really tiny and each seed contain only about 5% of oil in it at most, plus the seeds are usually handpicked from the fruits. This means it will take tons of these seeds to produce just one bottle of the oil for commercial purpose. But from its medical properties to its culinary importance, skin lightening, moisturizing, and protection abilities, down to its extraordinary hair care properties, prickly seed oil has got lots of excellent rewards for anyone who pays the price.
The platform combines the strengths of Singtel's extensive, intelligent network capabilities with Microsoft's cloud expertise to create a unique solution that sets new standards for IoT applications," said Mr Diomedes Kastanis, Head of IoT at Singtel. "Our solution provides speed, transparency and flexibility, paving the way for a more pervasive use of IoT to accelerate enterprises' digitalisation efforts. AI-powered intelligent connectivity over Microsoft Azure will be the fastest connected path for IoT innovators to scale globally, and the smartest path to cross-device synergy in an instrumented, connected world.
There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
ScaleMP is presenting at CloudEXPO 2019, held June 24-26 in Santa Clara, and we’d love to see you there. At the conference, we’ll demonstrate how ScaleMP is solving one of the most vexing challenges for cloud — memory cost and limit of scale — and how our innovative vSMP MemoryONE solution provides affordable larger server memory for the private and public cloud. Please visit us at Booth No. 519 to connect with our experts and learn more about vSMP MemoryONE and how it is already serving some of the world’s largest data centers. Click here to schedule a meeting with our experts and executives.
Darktrace is the world's leading AI company for cyber security. Created by mathematicians from the University of Cambridge, Darktrace's Enterprise Immune System is the first non-consumer application of machine learning to work at scale, across all network types, from physical, virtualized, and cloud, through to IoT and industrial control systems. Installed as a self-configuring cyber defense platform, Darktrace continuously learns what is ‘normal' for all devices and users, updating its understanding as the environment changes.