Home >Web Front-end >JS Tutorial >How to Parse XML Files in JavaScript Across Browsers?
Problem:
How can XML files be parsed in Javascript across browsers and platforms?
Solution:
The following Javascript code can be used to achieve cross-browser parsing:
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("<foo>Stuff</foo>"); alert(xml.documentElement.nodeName);
Live Demo:
This code works in all major browsers, including IE 6. Check out the live demo below:
[Live Demo Link]
The above is the detailed content of How to Parse XML Files in JavaScript Across Browsers?. For more information, please follow other related articles on the PHP Chinese website!