# 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文件
<?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>