2

I have the following, which loads XML from a web site and parses it:

function load() {
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = parse;
  xhttp.open('GET', 'http://...XML.xml', false);
  xhttp.send();
}

function parse() {
  xmlDoc = xhttp.responseXML.documentElement.childNodes;
  for (var i = 0; i < xmlDoc.length; i++) {
    nodeName = xmlDoc[i].nodeName;
    ...
}

After I loading this, I store it in localStorage and I can retrieve it as a string. I need to be able to convert it back to a xml document just like:

xmlDoc = xhttp.responseXML.documentElement.childNodes;

does, so i can parse it. I have been looking for awhile now and can not figure it out.

Thanks in advance.

1 Answers1

0

Based on the answer here XML parsing of a variable string in JavaScript Credit to @tim-down

You need to create an XML parser. Then pass the string into your parse instance. Then you should be able to query it as per before.

var parseXml;

if (typeof window.DOMParser != "undefined") {
    parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" &&
       new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    throw new Error("No XML parser found");
}

Example usage:

var xml = parseXml("[Your XML string here]");
Community
  • 1
  • 1
Scott
  • 21,211
  • 8
  • 65
  • 72