封装了3个XML常用的相关函数,注释已写好~。
1 function testXML2(){ 2 var xmldom = document.implementation.createDocument("", "root", null); 3 // alert(xmldom.documentElement.tagName); //"root" 4 var child = xmldom.createElement("child"); 5 xmldom.documentElement.appendChild(child); 6 7 xmldom.async = true; 8 xmldom.onreadystatechange = function(){ 9 if (xmldom.readyState == 4){ 10 if (xmldom.parseError != 0){ 11 alert("An error occurred:\nError Code: " 12 + xmldom.parseError.errorCode + "\n" 13 + "Line: " + xmldom.parseError.line + "\n" 14 + "Line Pos: " + xmldom.parseError.linepos + "\n" 15 + "Reason: " + xmldom.parseError.reason); 16 } else { 17 alert(xmldom.documentElement.tagName); //"root" 18 alert(xmldom.documentElement.firstChild.tagName); //"child" 19 var anotherChild = xmldom.createElement("child"); 20 xmldom.documentElement.appendChild(anotherChild); 21 var children = xmldom.getElementsByTagName("child"); 22 alert(children.length); //2 23 alert(xmldom.xml); 24 } 25 } 26 }; 27 xmldom.load("example.xml"); 28 } 29 // 解析 XML ,跨浏览器方法 30 // parseXml()函数只接收一个参数,即可解析的 XML 字符串 31 function parseXml(xml){ 32 var xmldom = null; 33 if (typeof DOMParser != "undefined"){ 34 xmldom = (new DOMParser()).parseFromString(xml, "text/xml"); 35 var errors = xmldom.getElementsByTagName("parsererror"); 36 if (errors.length){ 37 throw new Error("XML parsing error:" + errors[0].textContent); 38 } 39 } else if (typeof ActiveXObject != "undefined"){ 40 xmldom = createDocument(); 41 xmldom.loadXML(xml); 42 if (xmldom.parseError != 0){ 43 throw new Error("XML parsing error: " + xmldom.parseError.reason); 44 } 45 } else { 46 throw new Error("No XML parser available."); 47 } 48 return xmldom; 49 } 50 // 序列化 XML ,跨浏览器方法 51 // serializeXml()函数接收一个参数,即要序列化的 XML DOM 文档 52 function serializeXml(xmldom){ 53 if (typeof XMLSerializer != "undefined"){ 54 return (new XMLSerializer()).serializeToString(xmldom); 55 } else if (typeof xmldom.xml != "undefined"){ 56 return xmldom.xml; 57 } else { 58 throw new Error("Could not serialize XML DOM."); 59 } 60 }
// 以异步方式加载 XML 文件的典型模式
原文地址:https://www.cnblogs.com/mhxy13867806343/p/8447160.html
时间: 2024-10-15 21:09:18