使用javascript脚本读取xml文件,这里暂只考虑IE浏览器
step1 创建DOM对象
/**
* 读取xml文件
*
* @param
* @arrange (512.笔记) jb51.cc
**/
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文件
/**
* 加载xml文件
*
* @param
* @arrange (512.笔记) jb51.cc
**/
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,快速定位节点 原文链接:https://www.f2er.com/js/527778.html