今天在csdn上面看到有位朋友提出js读取xml节点里面的属性。觉得是个不错的建议,本人也写过【JS读取XML并显示各节点[兼容IE/FF/Chrome,Safari]】,只读取节里面的值,所以还是完善下比较好,所以就自己写了个。希望能帮到大家。效果图如下:
xml数据内容
<?xml version="1.0" encoding="utf-8"?>
<markers>
<marker carId="1" carName="SHANGHAI" gpsTime="2011-08-26 21:21:11.0" lat="31.230393" lng="121.473704" direction="222" speed="22" />
<marker carId="7" carName="XIAMEN" gpsTime="2011-08-26 21:21:11.0" lat="24.479836" lng="118.089421" direction="222" speed="22" />
</markers>
源代码如下:
<!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=gb2312" />
<title>js解析xml(如何获取某节点的属性)</title>
<style>
li{list-style:none;}
</style>
<script type="text/javascript">
//==============================================================
var orderDoc;
//获取xml文件
function loadXmlFile(xmlFile){
var xmlDom = null;
if (window.ActiveXObject){
xmlDom = new ActiveXObject("Microsoft.XMLDOM");
xmlDom.async=false;
xmlDom.load(xmlFile)||xmlDom.loadXML(xmlFile);//如果用的是XML字符串//如果用的是xml文件
}else if (document.implementation && document.implementation.createDocument){
var xmlhttp = new window.XMLHttpRequest();
xmlhttp.open("GET", xmlFile, false);
xmlhttp.send(null);
xmlDom = xmlhttp.responseXML;
}else{
xmlDom = null;
}
return xmlDom;
}
//读取属性的值
function getAttributeValue (xmlNode,attrName){
if(!xmlNode)return "" ;
if(!xmlNode.attributes) return "" ;
if(xmlNode.attributes[attrName]!=null) return xmlNode.attributes[attrName].value ;
if(xmlNode.attributes.getNamedItem(attrName)!=null) return xmlNode.attributes.getNamedItem(attrName).value ;
return "" ;
}
var stringsss="";
//根据编号获取数据
function getDataByid(number)
{
var t1 =getAttributeValue(orderDoc.getElementsByTagName("marker")[number],"carId");
var t2 =getAttributeValue(orderDoc.getElementsByTagName("marker")[number],"carName");
var t3 =getAttributeValue(orderDoc.getElementsByTagName("marker")[number],"gpsTime");
var t4 =getAttributeValue(orderDoc.getElementsByTagName("marker")[number],"lat");
var t5 =getAttributeValue(orderDoc.getElementsByTagName("marker")[number],"lng");
var t6 =getAttributeValue(orderDoc.getElementsByTagName("marker")[number],"direction");
var t7 =getAttributeValue(orderDoc.getElementsByTagName("marker")[number],"speed");
var std='<li><b>carId:'+(t1)+'</b><br><b>carName:'+(t2)+'</b><br><b>gpsTime:'+(t3)+'</b><br><b>lat:'+(t4)+'</b><br><b>lng:'+(t5)+'</b><br><b>direction:'+(t6)+'</b><br><b>speed:'+(t7)+'</b></li>';
return std;
}
//获得页面内容
function getContent(){
orderDoc=loadXmlFile("http://www.86y.org/download/had.xml");
var items=orderDoc.getElementsByTagName("marker").length;
var htmlstr="";
stringsss+='<ul>';
for(i=0;i<items;i++){
stringsss+=getDataByid(i);
}
stringsss+='</ul>'
document.write(stringsss);
}
</script>
</head>
<body>
</body>
<script type="text/javascript" language="javascript">
getContent();
</script>
</html>
完了。