JS加载&解析XML文件的浏览器兼容处理


JS加载XML,浏览器之间有差异,代码如下

  this.createXMLDom = function() {
    var xmldoc;
    var xmlFile = "XXXXXXXXX.xml";
    if (window.ActiveXObject) {
      xmldoc = new ActiveXObject("Microsoft.XMLDOM");
      xmldoc.async = false;
      //和FireFox一致,设为true;
      xmldoc.preserveWhiteSpace = true;
      xmldoc.load(xmlFile);
    }
    //firefox
    else if (navigator.userAgent.indexOf("Firefox") > 0) {
      xmldoc = document.implementation.createDocument("", "doc", null);
      xmldoc.async = false;
      xmldoc.load(xmlFile);
    }
    //chrome
    else {
      var xmlhttp = new window.XMLHttpRequest();
      xmlhttp.open("GET", xmlFile, false);
      xmlhttp.send(null);
      if (xmlhttp.readyState === 4) {
          xmldoc = xmlhttp.responseXML.documentElement;
      }
    }
    return xmldoc;
  }

解析XML

  //加载XML文件
  var xmlDom = _this.createXMLDom();
  var elements = xmlDom.getElementsByTagName("data");
  var data = "";
  for (var i = 0; i < elements.length; i++) {
      var name = elements[i].getElementsByTagName("name")[0].firstChild.nodeValue;
      var path = elements[i].getElementsByTagName("path")[0].firstChild.nodeValue;
      data += "mingcen:";
      data += name;
      data += " path:";
      data += path;
      data += " ";
  }
  alert(data);

  //从xml中获取节点内容

  function getXmlNode(str){
    var str = "xml字符串内容";
    //创建文档对象
    var parser=new DOMParser();
    var xmlDoc=parser.parseFromString(str,"text/xml");

    //提取数据
    var countrys = xmlDoc.getElementsByTagName('DataSource');

    var arr = [];

    for (var i = 0; i < countrys.length; i++) {
      arr.push(countrys[i].textContent);
    };
    //console.log(arr);
    return arr;
  }

  //将数据转成json格式
  function infoToJson(str){
    var s = getXmlNode(str);
    // console.log(s);
    //转成json格式
    var obj = eval('(' + s + ')');
    // console.log(obj);

    //输出json
    console.log(obj[0].id)
    return obj;
  }

示例XML文件

  <?xml version="1.0" encoding="gb2312"?>
  <root>
    <data id="1">
      <name>formal</name>
      <path>XXXXXXXXXXXXX</path>
    </data>
    <data id="2">
      <name>test</name>
      <path>YYYYYYYYYYYYY</path>
    </data>
  </root>