The method for reading XML files using JS Because xml needs to be parsed on the project, Baidu summarized the xml parsing methods of various mainstream browsers, he can only be very simple to know his usage, but there is no in-depth research.
Different browsers use different xml parsing methods. Currently, there are roughly three types of mainstream browsers:
First, the ie ancestor: js provides a method for creating Automation objects, new ActiveXObject ("Microsoft. XMLDOM ");
Class 2: firefox and opera: instantiate the DOMParser object with the constructor DOMParser (), parse the xml text, and return the xml Document object;
Category 3: chrome and safari: Because chrome does not support the load method, the http protocol and XMLHttpRequest object are used.
Code:
Function loadXML () {var xmlDoc; try {// IExmlDoc = new ActiveXObject ("Microsoft. XMLDOM ");} catch (e) {// firefox, operaxmlDoc = document. implementation. createDocument ("", "", null);} try {xmlDoc. asyc = false; // whether to asynchronously call xmlDoc. load ("xxx. xml "); // file path} catch (e) {// chromevar xmlhttp = new window. XMLHttpRequest (); xmlhttp. open ("GET", "xxx. xml ", false); // create a new http request, and specify the request method, URL, and authentication information xmlDoc = xmlhttp. responseXML;} return xmlDoc ;}
The returned xmlDoc object. The property documentElement contains various values of the xml node, which can be found on the console.
Ps: If you are reading local xml files, chrome prohibits access to local files by default. You need to add the startup parameter -- allow-file-access-from-files.