Home > Article > Web Front-end > How to read XML files using JS
Since the project needs to parse xml, various Baidu and then summarized the methods of parsing xml in various mainstream browsers. I can only know its usage very briefly, but there is no in-depth research.
Different browsers parse xml in different ways. According to the current mainstream browsers, they are roughly divided into three categories:
The first category, the ancestor of ie: js provides a method for creating Automation objects, new ActiveXObject("Microsoft.XMLDOM" );
Second category: firefox, opera: Use the constructor DOMParser() to instantiate the DOMParser object, parse the xml text, and return the xml Document object;
Category 3: chrome, safari: Since chrome does not support the load method, Therefore, the http protocol and XMLHttpRequest object are used.
Code:
function loadXML(){ var xmlDoc; try{ //IE xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); }catch(e){ //firefox,opera xmlDoc = document.implementation.createDocument("","",null); } try{ xmlDoc.asyc = false; //是否异步调用 xmlDoc.load("xxx.xml"); //文件路径 }catch(e){ //chrome var xmlhttp = new window.XMLHttpRequest(); xmlhttp.open("GET","xxx.xml",false); //创建一个新的http请求,并指定此请求的方法、URL以及验证信息 xmlDoc = xmlhttp.responseXML; } return xmlDoc; }
The xmlDoc object returned, the attribute documentElement contains various values of the xml node, you can console it and find it slowly.
ps: If you are reading local xml, chrome prohibits access to local files by default, and you need to add the startup parameter --allow-file-access-from-files.