跨浏览器Javascript xml解析

跨浏览器Javascript xml解析

有没有跨浏览器/跨平台的方法来解析Javascript中的XML文件?



白衣染霜花
浏览 406回答 3
3回答

BIG阳

以下内容将适用于所有主要浏览器,包括IE 6:var&nbsp;parseXml;if&nbsp;(typeof&nbsp;window.DOMParser&nbsp;!=&nbsp;"undefined")&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;parseXml&nbsp;=&nbsp;function(xmlStr)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;(&nbsp;new&nbsp;window.DOMParser()&nbsp;).parseFromString(xmlStr,&nbsp;"text/xml"); &nbsp;&nbsp;&nbsp;&nbsp;};}&nbsp;else&nbsp;if&nbsp;(typeof&nbsp;window.ActiveXObject&nbsp;!=&nbsp;"undefined"&nbsp;&& &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;new&nbsp;window.ActiveXObject("Microsoft.XMLDOM"))&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;parseXml&nbsp;=&nbsp;function(xmlStr)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;xmlDoc&nbsp;=&nbsp;new&nbsp;window.ActiveXObject("Microsoft.XMLDOM"); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;xmlDoc.async&nbsp;=&nbsp;"false"; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;xmlDoc.loadXML(xmlStr); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;xmlDoc; &nbsp;&nbsp;&nbsp;&nbsp;};}&nbsp;else&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;throw&nbsp;new&nbsp;Error("No&nbsp;XML&nbsp;parser&nbsp;found");}示例用法:var&nbsp;xml&nbsp;=&nbsp;parseXml("<foo>Stuff</foo>");alert(xml.documentElement.nodeName);现场演示:var parseXml;if (typeof window.DOMParser != "undefined") {&nbsp; &nbsp; parseXml = function(xmlStr) {&nbsp; &nbsp; &nbsp; &nbsp; return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");&nbsp; &nbsp; };} else if (typeof window.ActiveXObject != "undefined" &&&nbsp; &nbsp; &nbsp; &nbsp;new window.ActiveXObject("Microsoft.XMLDOM")) {&nbsp; &nbsp; parseXml = function(xmlStr) {&nbsp; &nbsp; &nbsp; &nbsp; var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");&nbsp; &nbsp; &nbsp; &nbsp; xmlDoc.async = "false";&nbsp; &nbsp; &nbsp; &nbsp; xmlDoc.loadXML(xmlStr);&nbsp; &nbsp; &nbsp; &nbsp; return xmlDoc;&nbsp; &nbsp; };} else {&nbsp; &nbsp; throw new Error("No XML parser found");}var xml = parseXml("<foo>Stuff</foo>");document.body.innerHTML = "Root element: " + xml.documentElement.nodeName;
打开App,查看更多内容
随时随地看视频慕课网APP