xml字符串转对象xml文件转对象

时间:2022-12-28 22:25:31

判断是否是ie浏览器和非ie浏览器的方法有多种,在此只介绍用例中的方法:

1、解析xml字符串,得到xml对象的方式:

  1. function createXml(str){
  2.   if(document.all){//IE浏览器
  3.   var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  4. xmlDoc.async = false;
  5.   xmlDoc.loadXML(str);
  6.   return xmlDoc;
  7.   }
  8.   else{//非IE浏览器
  9.           return new DOMParser().parseFromString(str, "text/xml");
  10. }
  11. }

2、解析xml文件,将其转换为xml对象的方式:

  1. /**
  2. * aXMLFileName是xml文件路径名
  3. */
  4. function getXmlDoc(){
  5. try{
  6. if (window.ActiveXObject){
  7. xmlDoc= new ActiveXObject("Microsoft.XMLDOM");
  8. xmlDoc.async = false;
  9. isLoaded = xmlDoc.load(aXMLFileName);
  10. }
  11. else if(document.implementation&& document.implementation.createDocument){
  12. try{
  13. xmlDoc = document.implementation.createDocument('', '', null);
  14. xmlDoc.async = false;
  15. xmlDoc.load(aXMLFileName);
  16. } catch(e){
  17. var xmlhttp = new window.XMLHttpRequest();
  18. xmlhttp.open("GET",aXMLFileName,false);
  19. xmlhttp.send(null);
  20. xmlDoc = xmlhttp.responseXML;
  21. }
  22. }
  23. else{
  24. alert("load data error");
  25. }
  26. }
  27. catch(e){
  28. alert(e.message);
  29. }
  30. }

本文出自 “猪会飞” 博客,请务必保留此出处http://jiyanle.blog.51cto.com/6932197/1529727