JavaScript获取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>
效果图: