一个遍历XML所有节点的递归代码[javascript+DOM方式]
遍历DOM节点.xml:
<?xml version="1.0"encoding="UTF-8"?>
<customers>
<customer ID="TT89"ID2="TT89">
<username>Jerry</username>
<address>
<city>guilin</city>
<zipcode>541004</zipcode>
</address>
</customer>
</customers>
遍历DOM节点.htm:
<scriptlanguage="javascript">
var xmlDoc = new ActiveXObject("Msxml2.DOMDocument");
xmlDoc.async = false;
xmlDoc.load("遍历DOM节点.xml");
var root = xmlDoc.documentElement;
Recursion(root);
function Recursion(o){
if(o.nodeType==1 || o.nodeType==2){
document.write(o.nodeName);
}
if(o.attributes){
for(i=0;i<o.attributes.length;i++){
format =(i>0)?" ":":";
document.write(format+o.attributes[i].nodeName+"="+o.attributes[i].text);
}
}
if(o.hasChildNodes&& o.firstChild.nodeType!=3){
document.write("<br>");
returnarguments.callee(o.childNodes[0]);
}else{
document.write(":"+o.text);
document.write("<br>");
returnarguments.callee(o.nextSibling);
}
}
</script>
运行结果:
customers
customer:ID=TT89 ID2=TT89
username:Jerry
address
city:guilin
zipcode:541004
因为是应答疑所写,所以,以上代码并没有太多关注XML的nodeType问题,故通用性不是太强,另外,也没有考虑到浏览器兼容的问题,但递归的思路是通用的。
Qr
回复:一个遍历XML所有节点的递归代码[javascript+DOM方式]
2011-11-13 16:10:14
个人主页 | 引用回复 | 主人回复 | 返回 | 编辑 | 删除
<address>中包函了文本节点,所以,仅判断nodeType=1或2是行不通的,需要增加对文本节点的判断。文本节点的nodeType=3。
Qr
回复:一个遍历XML所有节点的递归代码[javascript+DOM方式]
2011-11-12 11:11:22
个人主页 | 引用回复 | 主人回复 | 返回 | 编辑 | 删除
很不错,不过我觉得有点遗憾,如果我们的xml文件变成这样,就不能很好的循环遍历我们的数据。
<?xml version="1.0"encoding="UTF-8"?>
<customers>
<customerID="TT89" ID2="TT89">
<username>湖北</username>
<address>主要的城市的和邮政编码
<city>黄石</city>
<code>435005</code>
</address>
</customer>
<customer ID="TT87" ID2="TT87">
<username>江西</username>
<address>
<city>南昌</city>
<code>369000</code>
</address>
</customer>
</customers>
运行的结果是:
customers
customer:ID=TT89 ID2=TT89
username:湖北
address:主要的城市的和邮政编码 黄石 435005
不知道有解决的办法没有,用你这种递归方法。
相关链接:http://www.cnblogs.com/jingyi/archive/2012/07/12/2588521.html