Posted in Javascript onAugust 05, 2013
使用JS读取xml文件,这里暂只考虑IE浏览器
step1 创建DOM对象
function createDom() { var xmlDoc = null; try { //IE if (typeof arguments.callee.activeXString != 'string') { var versions = [ "MSXML2.DOMDocument.6.0", "MSXML2.DOMDocument.3.0", "MSXML2.DOMDocument", "Microsoft.XMLDOM" ]; var i, len; for (i = 0, len = versions.length; i < len; ++i) { try { new ActiveXObject(versions[i]); arguments.callee.activeXString = versions[i]; break; } catch (ex) { // ignore } } } xmlDoc = new ActiveXObject(arguments.callee.activeXString); } catch (ex) { // other xmlDoc = document.implementation.createDocument("", "", null); } return xmlDoc; }
IE8以前,XmlDom都是利用ActiveX对象实现的,在IE9之后,IE开始支持Level 2级DOM,(其他支持Level 2 DOM的浏览器包括Firefox, Opera, Chrome, and Safari等)
可以像下面一样创建XML DOM对象:
var xmldom = document.implementation.createDocument(namespaceUri, root, doctype);
step2 加载xml文件
function loadXML(file) { var dom = createDom(); if (dom == null) { alert("load filed!"); } try { dom.async = false; dom.load(file); } catch (ex) { alert("unsupport browser!"); } return dom; }
一个简单的例子:
var xmlDom = loadXML("config.xml");
IE下,可以调用selectNodes() 和selectSingleNode()方法,利用XPath,快速定位节点
IE下JS读取xml文件示例代码
声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@