Tuesday, February 22, 2011

Parse XML String into DOM with Javascript

You can use following function to convert any XML string into a DOM object from a browser.
function parseXML(xml) {
    xml = xml.replace(/^[\s\n\r\t]*[<][\?][xml][^<^>]*[\?][>]/, "");
    var doc;
    if (window.ActiveXObject) {
        doc = new ActiveXObject("Microsoft.XMLDOM");
        doc.async = false;
        doc.loadXML(xml);
    } else
        doc = (new DOMParser()).parseFromString(xml, "application/xml");
    return doc;
}

2 comments: