Thursday, October 13, 2011

How to parse an XML return across browser and return an XML object via jQuery.

I came to across to a problem where I can't parse the XML return from the REST URL using jQuery on IE browser.

Since our best friend IE has another way of thinking, I come up with a function that cater all XML parsing (across browser).

The function below parseXMLToObj will accept parameter xmlData, which can either be an object or an XML string.

The function will return the converted XML object which you can use in doing some jQuery stuff.

You can download jQuery from here: http://code.jquery.com/jquery-latest.js


function parseXMLToObj(xmlData) {
        if ($.isXMLDoc(xmlData) || !$.browser.msie || ($.browser.msie && document.documentMode == 9)) {
                return $(xmlData);
        } else {
                var xmlDoc = $.parseXML(xmlData);
                return $(xmlDoc);
        }
}


Sample Usage:

var xmlData = "<results><data>1</data><data>2</data></results>";
parseXMLToObj(xmlData);


Goodluck! Happy coding!!

No comments:

Post a Comment