//跨浏览器获取xmlDom
1 function getXMLDOM(xmlStr) { 2 var xmlDom = null; 3 if (typeof window.DOMParser != 'undefined') { 4 xmlDom = (new DOMParser).parseFromString(xmlStr,'text/xml'); //创建xmlDom对象 5 var errors = xmlDom.getElementsByTagName('parsererror'); 6 if(errors.length > 0) { 7 throw new Error('XML格式有误:'+errors[0].textContent); 8 } 9 return xmlDom; 10 } else if (typeof window.ActiveXObject != 'undefined') { 11 var version = [ 12 'MSXML2.DOMDocument.6.0', 13 'MSXML2.DOMDocument.3.0', 14 'MSXML2.DOMDocument' 15 ]; 16 for(var i=0;i<version.length;i++) { 17 try { 18 var xmlDom = new ActiveXObject(version[i]); 19 } catch (e) { 20 //遇到错误跳过,继续执行try 21 } 22 } 23 xmlDom.loadXML(xmlStr); 24 if(xmlDom.parseError != 0) { //使用 !+ 号 25 throw new Error('错误信息为:' + xmlDom.parseError.reason); 26 } 27 return xmlDom; 28 } else { 29 throw new Error('系统或浏览器不支持xmlDom对象!'); 30 } 31 return xmlDom; 32 }
/*
DOM2没有序列化XML的属性,XMLSerializer类型来帮助序列化XML字符串。
IE9、Safari、Chrome和Opera都支持这个类型。
*/
1 function serializerXML(xmlDom) { 2 var xml = null; 3 if(typeof window.XMLSerializer != 'undefined') {//w3c的序列化 4 var serializer = new XMLSerializer(); 5 xml = serializer.serializeToString(xmlDom); 6 } else if(typeof xmlDom.xml != 'undefined') { //ie直接序列化 7 xml = xmlDom.xml; 8 } 9 return xml; 10 }
//跨浏览器获取xml单一节点
1 function selectSingleNode(xmlDom,xpath) { 2 var node = null; 3 if(typeof xmlDom.evaluate != 'undefined') { //w3c 4 var patt = /[(d+)]/; 5 var num = null; 6 var flag = xpath.match(patt); 7 if (flag) { 8 num = parseInt(RegExp.$1) + 1;//w3c下标从1开始,如0加1 9 xpath = xpath.replace(patt,'['+num+']'); //root/user[1] 10 } 11 var result = xmlDom.evaluate(xpath,xmlDom,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null); 12 if(result != null) { 13 node = result.singleNodeValue; //w3c默认的下标是1 14 } 15 } else if (typeof xmlDom.selectSingleNode != 'undefined') {//ie中unknown而非 undefined 16 node = xmlDom.selectSingleNode(xpath); 17 } 18 return node; 19 }
//跨浏览器获取xml所有节点
1 function selectNodes(xmlDom,xpath) { 2 var nodes = []; 3 if(typeof xmlDom.evaluate != 'undefined') { //w3c 4 var patt = /[(d+)]/; 5 var num = null; 6 var flag = xpath.match(patt); 7 if(flag) { 8 num = parseInt(RegExp.$1) + 1; 9 xpath = xpath.replace(patt,'['+num+']'); 10 } 11 var result = xmlDom.evaluate(xpath,xmlDom,null,XPathResult.ORDERED_NODE_ITERATOR_TYPE,null); 12 var node = null; 13 if(result != null) { 14 while ((node = result.iterateNext()) !== null) { 15 nodes.push(node); 16 } 17 } 18 } else if (typeof xmlDom.selectNodes != 'undefined') { //unkonwn 19 nodes = xmlDom.selectNodes(xpath); 20 } 21 return nodes; 22 }
1 var xmlStr = '<root><name id="d1">du1</name><name id="d2">du2</name></root>'; 2 var xmlDom = getXMLDOM(xmlStr); 3 var nodes = selectNodes(xmlDom,'root/name'); 4 //alert(nodes.length); 5 //alert(serializerXML(xmlDom)); //序列化xmlStr 6 //alert(serializerXML(selectSingleNode(xmlDom,'root/name[0]'))); //序列化单一节点 7 8 alert(serializerXML(nodes[0]));//<name id="d1">du1</name> 9 alert(serializerXML(nodes[1]));