问题
I'm attempting to read local file (that user inputted) as xml. Following code stright up fails due to the fact that global 'xml' variable remains null in all other scopes. Not sure why considering there's no local variable named 'xml'. Unless user changes the file in which case 'xml' variable is a proper xml document. I'm also confused by alert order. How do FileReader() and DomParser() actually behave?
var xml = null; //global
function readFile(object) { //object is document.getElementById('fileInput')
var file = object.files[0]
var reader = new FileReader()
reader.onload = function() {
var parser = new DOMParser();
xml = parser.parseFromString(reader.result,"text/xml"); //window.xml does nothing
if (xml.documentElement.nodeName == 'parseerror'){
alert("Never actually appears");
}
alert("Appears last");
}
alert("Appears first");
reader.readAsText(file);
}
来源:https://stackoverflow.com/questions/64680423/reading-local-text-file-as-xml