這篇文章主要介紹了JavaScript獲取XML數據的方法,需要的朋友可以參考下
Hot.xml文件 : 代碼如下: <?xml version="1.0" encoding="gb2312"?> <root> <item> <name>劉亦菲</name> <url>MingXing/LiuYiFei.htm</url> <color>red</color> </item> <item> <name>蔡依林</name> <url>MingXing/CaiYiLin.htm</url> <color>blue</color> </item> <item> <name>張娜拉</name> <url>MingXing/ZhangNaLa.htm</url> <color>green</color> </item> <item> <name>張韶涵</name> <url>MingXiang/ZhangShaoHan.htm</url> <color>grey</color> </item> <item> <name>張靓穎</name> <url>MingXing/ZhangLiangYin.htm</url> <color>black</color> </item> <item> <name>李宇春</name> <url>MingXing/LiYuChun.htm</url> <color>yellow</color> </item> <item> <name>徐若瑄</name> <url>MingXing/XuLuXuan.htm</url> <color>pink</color> </item> </root> demo1.html文件: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>JavaScript獲取XML數據</title> <script language="javascript"> 代碼如下: var xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); //創建XmlDom對象 xmlDoc.async=true; //使用異步加載 xmlDoc.onreadystatechange=loadedSales; function loadedSales() { var txt=""; if(xmlDoc.readyState == 0){ alert("0"); } if(xmlDoc.readyState == 1){ alert("1"); } if(xmlDoc.readyState == 2){ alert("2"); } if(xmlDoc.readyState == 3){ alert("3"); } if(xmlDoc.readyState == 4) { if(xmlDoc.parseError.errorCode != 0) { txt="xml解析錯誤!"; }else{ var items=xmlDoc.documentElement.selectNodes("item"); if(items != null && items.length > 0) { for(var i=0; i < items.length; i++) { txt += "<li><a href="+items[i].childNodes[1].text+" mce_href="+items[i].childNodes[1].text+" style="color:" mce_style="color:""+items[i].childNodes[2].text+">"+items[i].childNodes[0].text+"</a></li>"; } }else{ txt=""; } } }else{ txt=""; } document.getElementById("sales").innerHTML=txt; } function loadXmlDoc() { var url="Hot.xml"; xmlDoc.load(url); } </script> </head> <body onLoad="loadXmlDoc()"> <div id="sales"></div> </body> </html>