1 /** 2 * Created by Administrator on 2015/4/4. 3 */ 4 5 var XmlUtil=(function () { 6 var createDocument= function () { 7 if(typeof arguments.callee.activeXString !=‘string‘){ 8 var versions=[‘MSXML2.DOMDocument.6.0‘,‘MSXML2.DOMDocument.3.0‘,‘MSXML2.DOMDocument‘], 9 i,len; 10 for(i=0,len=versions.length;i<len;i++){ 11 try{ 12 new ActiveXObject(versions[i]); 13 arguments.callee.activeXString=versions[i]; 14 break; 15 }catch (e){ 16 //跳过 17 } 18 } 19 } 20 return new ActiveXObject(arguments.callee.activeXString); 21 }; 22 return { 23 //把xml字符串序列化成XMLDOM对象 24 parseXML:function(xml){ 25 var xmldom=null; 26 if(DOMParser != ‘undefined‘){ 27 var domparser=new DOMParser(); 28 xmldom= domparser.parseFromString(xml,‘text/xml‘); 29 var errorElment=xmldom.getElementsByTagName(‘parsererror‘); 30 if(errorElment.length>0){ 31 throw new Error(‘XML PARSER ERROR:‘+errorElment[0].textContent); 32 } 33 }else if(typeof ActiveXObject != ‘undefined‘){ 34 xmldom=createDocument(); 35 xmldom.loadXML(xml); 36 if(xmldom.parseError != 0){ 37 throw new Error(‘XML PARSING ERROR:‘+xmldom.parseError.reason); 38 } 39 }else{ 40 throw new Error(‘NO XML PARSER AVAILABLE‘); 41 } 42 return xmldom; 43 }, 44 //把xmldom对象序列话成xml对象 45 serializeXml:function(xmldom){ 46 if(typeof XMLSerializer !=‘undefined‘){ 47 return new XMLSerializer().serializeToString(xmldom); 48 }else if(typeof xmldom.xml !=‘undefined‘){ 49 return xmldom.xml; 50 }else{ 51 throw new Error(‘Could not serialize xml dom‘); 52 } 53 } 54 } 55 56 }());
用法
1 var xmldom=XmlUtil.parseXML(‘<root><child/></root>‘); 2 console.log(xmldom); 3 console.log(XmlUtil.serializeXml(xmldom));
时间: 2024-10-25 00:50:56