javascript跨浏览器操作xml

//跨浏览器获取xmlDom

 function getXMLDOM(xmlStr) {
var xmlDom = null;
if (typeof window.DOMParser != 'undefined') {
xmlDom = (new DOMParser).parseFromString(xmlStr,'text/xml'); //创建xmlDom对象
var errors = xmlDom.getElementsByTagName('parsererror');
if(errors.length > 0) {
throw new Error('XML格式有误:'+errors[0].textContent);
}
return xmlDom;
} else if (typeof window.ActiveXObject != 'undefined') {
var version = [
'MSXML2.DOMDocument.6.0',
'MSXML2.DOMDocument.3.0',
'MSXML2.DOMDocument'
];
for(var i=0;i<version.length;i++) {
try {
var xmlDom = new ActiveXObject(version[i]);
} catch (e) {
//遇到错误跳过,继续执行try
}
}
xmlDom.loadXML(xmlStr);
if(xmlDom.parseError != 0) { //使用 !+ 号
throw new Error('错误信息为:' + xmlDom.parseError.reason);
}
return xmlDom;
} else {
throw new Error('系统或浏览器不支持xmlDom对象!');
}
return xmlDom;
}

/*
DOM2没有序列化XML的属性,XMLSerializer类型来帮助序列化XML字符串。
IE9、Safari、Chrome和Opera都支持这个类型。
*/

 function serializerXML(xmlDom) {
var xml = null;
if(typeof window.XMLSerializer != 'undefined') {//w3c的序列化
var serializer = new XMLSerializer();
xml = serializer.serializeToString(xmlDom);
} else if(typeof xmlDom.xml != 'undefined') { //ie直接序列化
xml = xmlDom.xml;
}
return xml;
}

//跨浏览器获取xml单一节点

 function selectSingleNode(xmlDom,xpath) {
var node = null;
if(typeof xmlDom.evaluate != 'undefined') { //w3c
var patt = /\[(\d+)\]/;
var num = null;
var flag = xpath.match(patt);
if (flag) {
num = parseInt(RegExp.$1) + 1;//w3c下标从1开始,如0加1
xpath = xpath.replace(patt,'['+num+']'); //root/user[1]
}
var result = xmlDom.evaluate(xpath,xmlDom,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null);
if(result != null) {
node = result.singleNodeValue; //w3c默认的下标是1
}
} else if (typeof xmlDom.selectSingleNode != 'undefined') {//ie中unknown而非 undefined
node = xmlDom.selectSingleNode(xpath);
}
return node;
}

//跨浏览器获取xml所有节点

 function selectNodes(xmlDom,xpath) {
var nodes = [];
if(typeof xmlDom.evaluate != 'undefined') { //w3c
var patt = /\[(\d+)\]/;
var num = null;
var flag = xpath.match(patt);
if(flag) {
num = parseInt(RegExp.$1) + 1;
xpath = xpath.replace(patt,'['+num+']');
}
var result = xmlDom.evaluate(xpath,xmlDom,null,XPathResult.ORDERED_NODE_ITERATOR_TYPE,null);
var node = null;
if(result != null) {
while ((node = result.iterateNext()) !== null) {
nodes.push(node);
}
}
} else if (typeof xmlDom.selectNodes != 'undefined') { //unkonwn
nodes = xmlDom.selectNodes(xpath);
}
return nodes;
}
 var xmlStr = '<root><name id="d1">du1</name><name id="d2">du2</name></root>';
var xmlDom = getXMLDOM(xmlStr);
var nodes = selectNodes(xmlDom,'root/name');
//alert(nodes.length);
//alert(serializerXML(xmlDom)); //序列化xmlStr
//alert(serializerXML(selectSingleNode(xmlDom,'root/name[0]'))); //序列化单一节点 alert(serializerXML(nodes[0]));//<name id="d1">du1</name>
alert(serializerXML(nodes[1]));
上一篇:javascript跨浏览器事件对象类库


下一篇:Javascript跨浏览器的事件对象