Friday, November 2, 2012

XMLDocument in javascript

XML was so popular in XHR calls before JSON, and at that time (before jQuery) web developers used native Javascript APIs to convert XML string to XMLDocument (DOMParser) and vice versa (XMLSerializer). The following 2 functions are examples.

function StringtoXML(str) {
    // second parameter mimetype is required
    return (new DOMParser()).parseFromString(str, 'text/xml')
}

function XMLtoString(xmldoc){
    var serialized;
    try {
        serialized = (new XMLSerializer()).serializeToString(xmldoc);
    }
    catch (e) {
        // Internet Explorer has a different approach to serializing XML
        serialized = xmldoc.xml;
    }
    return serialized;
}

This pair is similar to JSON.parse and JSON.stringify for conversion between JSON object and String.

Now that we have jQuery, converting between XMLDocument and String is easier.
jQuery utitlity has 2 methods for XMLDocument
$.isXMLDoc() to test an XML document
$.parseXML() to parse String to XMLDocument

However, jQuery doesn't provide the utility method to convert XMLDocument to String. We can use above native window.XMLSerializer object.

Sometimes if we need manipulate XML data, we can wrap to jQuery object and leverage plenty of jQuery APIs. For instance, if we need change id attribute in XML data, we can use below methods.

$(xml).attr('id', 'new_id')[0].outerHTML
$("<p/>").append($(xml).attr('id', 'new_id')).html()

No comments:

Post a Comment