I am working on a project where I need to read a long(50,000 lines) XML file. I decided to use the default Javascript Document or XMLDocument classes instead of a third party XML parser. And DOM tree structure of default Javascript XML parser works well for my design because of how I need to traverse to child and parent nodes freely.
I tried using XMLHttpRequest in the following way:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "xmls/EXAMPLE.xml", true);
xhttp.send();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
console.log(xmlDoc.getElementsByTagName("example")[0].getAttributeNode("name").nodeValue);
}
This works especially with xmlDoc
object but after xhttp.send()
the document is not accesible anymore. I want the document to stay available because I need to access different parts of it at different times according to client choices.
I have also looked into DOMParser but I am not sure if it is an efficient way to convert 50,000 lines of text into string and then turn it into a Document object.
Such as var xmlDoc = new DOMParser().parseFromString(xml, "application/xml");
I have been looking into some questions in stack overflow and MDN but haven't been able to figure out an easy way to do this.
EDIT: When I make the xmlDoc variable global, I get the error "Cannot read property 'getElementsByTagName' of undefined". The following is how I tried to make it global:
var xmlDoc;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
xmlDoc = this.responseXML;
myFunction(this);
}
};
xhttp.open("GET", "xmls/EXAMPLE.xml", true);
xhttp.send();
function myFunction(xml) {
console.log(xmlDoc.getElementsByTagName("example")[0].getAttributeNode("name").nodeValue);
}
console.log(xmlDoc.getElementsByTagName("example")[0].getAttributeNode("name").nodeValue);
Here the console.log within "myFunction" works but the other one doesn't. I believe xmlDoc turns null after send().
Also this is literally everything I have in the javascript file, there is nothing else for the purposes of testing it.