0

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?

ceving
  • 21,900
  • 13
  • 104
  • 178

2 Answers2

1

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

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;
lexicore
  • 42,748
  • 17
  • 132
  • 221
  • What is the [maximum length](http://stackoverflow.com/a/2659995/402322) of a purely local get request? – ceving Jan 29 '15 at 09:27
  • This is an interesting but less efficient solution, because it makes it necessary to craft the request. The concatenation copies the XML string and the encoding also at least once, maybe even more than once. – ceving Jan 29 '15 at 09:39
  • @ceving Just another fallback. The last option. – lexicore Jan 29 '15 at 10:32