JS解析XML
XML文件:
<?xml version="1.0" encoding="gbk" ?>
<NewInfo>
<News>
<Title>今天要下雨</Title>
<Content>今天确实下雨了</Content>
<Date>2009-02-04</Date>
</News>
<News>
<Title>今天出太阳</Title>
<Content>今天确实出太阳了</Content>
<Date>2009-02-03</Date>
</News>
<News>
<Title>今天很无聊</Title>
<Content>今天确实很无聊</Content>
<Date>2009-02-02</Date>
</News>
</NewInfo>
HTML文件:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=gbk"/>
<title>JS读取XMLDemo</title>
<script language="javascript" type="text/javascript">
function NewInfoAction()
{
var dom;
var type=1; //默认为IE浏览器
var data = new Array(); //存储实体的数组
if(navigator.userAgent.indexOf("MSIE")>0)
{
dom = new ActiveXObject("Microsoft.XMLDOM"); //实例化dom对象
dom.async = false;
dom.load("b.xml"); //加载xml文件
window.alert('IE');
}
else if(isFirefox=navigator.userAgent.indexOf("Firefox") > 0)
{
type=2;
dom = document.implementation.createDocument("", "", null); //火狐不支持ActiveXObject
dom.async = false;
dom.load("b.xml");
}
else
{
window.alert('暂不识别该浏览器!');
return;
}
if(dom)
{
var node;
if(type == 1) //判断是否为IE浏览器
{
node = dom.documentElement.childNodes; //这里的node大家可以理解为net中的表,方便大家理解
for(var i=0;i<node.length;i++)
{
var title = node[i].childNodes[0].text; //取出i行中的字段的值,大家这样理解更方便
var content = node[i].childNodes[1].text;
var date = node[i].childNodes[2].text;
window.alert(title);
window.alert(content);
window.alert(date);
//data.push({title:title,content:content,date:date}); //在这里,我们使用使用json,把数据库存储在里面
}
}
else
{
var node = dom.getElementsByTagName("News");
for(var i=0;i<node.length;i++)
{
window.alert(dom.getElementsByTagName("News")[i].childNodes[1].textContent);
window.alert(dom.getElementsByTagName("News")[i].childNodes[3].textContent);
window.alert(dom.getElementsByTagName("News")[i].childNodes[5].textContent);
//var value = dom.getElementsByTagName("News")[i].textContent.split(' ');
//var title = value[4];
//var content = value[8];
//var date = value[12];
//data.push({title:title,content:content,date:date}); //在这里,我们使用使用json,把数据库存储在里面
}
}
}
else
{
window.alert("dom对象为空,失败了!");
return;
}
if(data.length != 0)
{
var shtml = '';
for(var i=0;i<data.length;i++)
{
shtml += '<div>';
shtml += '<div style="float:left; background-color:Red; width:80px; height:15px">';
shtml += data[i].title;
shtml += '</div>';
shtml += '<div>';
shtml += '<div style="float:left; background-color:Green;width:150px; height:15px">';
shtml += data[i].content;
shtml += '</div>';
shtml += '<div style="float:left; background-color:Green;width:120px; height:15px">';
shtml += data[i].date;
shtml += '</div>';
shtml += '</div>';
shtml += '</div>';
shtml += '<br/>';
}
document.getElementById('textDiv').innerHTML = shtml;
}
else
{
document.getElementById('textDiv').innerHTML = '没有信息!';
}
}
</script>
</head>
<body onload="NewInfoAction()">
<div id="textDiv" >
</div>
</body>
</html>