ceving
ceving

Reputation: 23794

How to parse a XML dom from a string?

It is possible to build a XML DOM from scratch:

var data = document.implementation.createDocument("", "", null);
data.appendChild(data.createElement("data"));

But I can not find a method which builds an XML DOM from a string (not URL):

var data = document.implementation.createDocument("", "", null);
data.parse_document("<data/>");

Do I have to write the parse_document from scratch or is it available somehow?

Upvotes: 0

Views: 170

Answers (2)

lexicore
lexicore

Reputation: 43651

In addition to T.J Crowder's answer, The Definitive Guide includes a third option:

var url = 'data:text/xml;charset=utf-8,' + encodeURIComponent(text);
var request = new XMLHttpRequest();
request.open('GET', url, false);
if (request.overrideMimeType) {
    request.overrideMimeType("text/xml");
}
request.send(null);
return request.responseXML;

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074038

From the code in your question, it looks like you're doing this on a browser.

If so, you can use DOMParser if it's available, falling back (on IE) to an active X object.

function parseXML(str) {
    var xmlDoc, parser;
    if (window.DOMParser) {
        parser = new DOMParser();
        xmlDoc = parser.parseFromString(str, "text/xml");
    } else {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(str);
    }
    return xmlDoc;
}

Note that parseXML will throw an exception on invalid XML.

Upvotes: 1

Related Questions