网站上很多用JS解析XML文档的资料或多或少都有点问题,
以下是自己总结的代码,用来解析XML文档,兼容各个浏览器。
parseXMLDOM.js代码:
/* * 纯JS解析XML文档(兼容各个浏览器) */ function parseXMLDOM(){ var _browserType = ""; var _xmlFile = ""; var _XmlDom = null; return { "getBrowserType" : function(){ return _browserType; }, "setBrowserType" : function(browserType){ _browserType = browserType; }, "getXmlFile" : function(){ return _xmlFile; }, "setXmlFile" : function(xmlFile){ _xmlFile = xmlFile; }, "getXmlDom" : function(){ return _XmlDom; }, "setXmlDom" : function(XmlDom){ _XmlDom = XmlDom; }, "getBrowserType" : function(){ var browserType = ""; if(navigator.userAgent.indexOf("MSIE") != -1){ browserType = "IE"; }else if(navigator.userAgent.indexOf("Chrome") != -1){ browserType = "Chrome"; }else if(navigator.userAgent.indexOf("Firefox") != -1){ browserType = "Firefox" } return browserType; }, "createXmlDom" : function(xmlDom){ if(this.getBrowserType() == "IE"){//IE浏览器 xmlDom = new ActiveXObject('Microsoft.XMLDOM'); xmlDom.async = false; xmlDom.load(this.getXmlFile()); }else{ var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", this.getXmlFile(), false); xmlhttp.send(null); xmlDom = xmlhttp.responseXML; } return xmlDom; }, "parseXMLDOMInfo" : function(){ var xmlDom = this.getXmlDom(); if(this.getBrowserType() == "IE"){ var bookObj = xmlDom.selectNodes("books/book"); if(typeof(bookObj) != "undifined"){ var strHtml=""; for(var i = 0; i < bookObj.length; i++){ strHtml += bookObj[i].selectSingleNode("isbn").text; strHtml += " "; strHtml += bookObj[i].selectSingleNode("price").text; strHtml += " "; strHtml += bookObj[i].selectSingleNode("title").text; if(i != bookObj.length - 1){ strHtml += "<br>"; } } } }else{ var book = xmlDom.getElementsByTagName("book"); var strHtml=""; for(var i = 0;i < book.length;i++){ strHtml += book[i].getElementsByTagName("isbn")[0].textContent; strHtml += " "; strHtml += " "; strHtml += book[i].getElementsByTagName("price")[0].textContent; strHtml += " "; strHtml += book[i].getElementsByTagName("title")[0].textContent; if(i != book.length - 1){ strHtml += "<br>"; } } } document.getElementById("msg").innerHTML = strHtml; } } } window.onload = function(){ var parseObj = new parseXMLDOM(); //设置浏览器类型 parseObj.setBrowserType(parseObj.getBrowserType()); //设置文件路径 parseObj.setXmlFile("test.xml"); //创建XMLDOM parseObj.setXmlDom(parseObj.createXmlDom(null)); //解析XMLDOM parseObj.parseXMLDOMInfo(); }
index.html代码:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JS解析XML文档中的数据(兼容所有浏览器)</title> <script language="javascript" type="text/javascript" src="https://www.jb51.net/js/parseXMLDOM.js"></script> </head> <body> <span></span> </body> </html>
test.xml代码:
<?xml version="1.0" encoding="UTF-8"?> <books> <book> <isbn>2207-1258-123</isbn> <price>25</price> <title>Javascript</title> </book> <book> <isbn>2207-1258-456</isbn> <price>50</price> <title>Ajax</title> </book> <book> <isbn>2207-1258-789</isbn> <price>75</price> <title>C#</title> </book> </books>