递规法遍历xml树的属性和节点值
注: function xml2javascript(xml_name,data) //参数xml_name: xml文档文件名,
//data:存储数据的数组对象名 转换成功后调用数组,基本按照dom的调用方法,只不过将'()'转换为'[]'
<SCRIPT LANGUAGE="JavaScript">
function xml2javascript(xml_name,data)
{
// +----------------------------------------------------+
// | 建立MSXML.DOMDocument |
var xml_doc = new ActiveXObject("MSXML.DOMDocument");
xml_doc.async = false;
xml_doc.load(xml_name);
// +----------------------------------------------------+
var obj = xml_doc.documentElement;
var data_obj = data;
eval_r(data_obj + "=new Object();");
_getXml(obj,data_obj)
}
function _getXml(obj,data_obj)
{
var node_count = obj.childNodes.length;
if (node_count == 0) { //如果没有子节点,那么返回
return;
}
eval_r(data_obj + ".childNodes=new Array();");
eval_r(data_obj + "._childNodes=new Array();");
for (var i=0; i<node_count; i++) {
if (obj.childNodes(i).nodeName == '#text') {
eval_r(data_obj + ".text=obj.text;"); //元素名称
return;
}
if (obj.childNodes(i).nodeName == '#cdata-section') {
eval_r(data_obj + ".text= obj.text;");
return;
}
eval_r(data_obj + ".childNodes[i]=new Object();"); //新建一个元素
eval_r(data_obj + ".childNodes[i].nodeName=obj.childNodes(i).nodeName;"); //元素名称
eval_r(data_obj + "._childNodes[obj.childNodes(i).nodeName]=i;"); //元素缓存
//属性
var attribute_count = obj.childNodes(i).attributes.length;
eval_r(data_obj + ".childNodes[i].attributes=new Array();"); //属性数组
eval_r(data_obj + ".childNodes[i]._attributes=new Array();"); //属性缓存数组
for (var j=0; j<attribute_count; j++) {
eval_r(data_obj + ".childNodes[i].attributes[j]=new Object();");
eval_r(data_obj + ".childNodes[i].attributes[j].nodeName=obj.childNodes(i).attributes(j).nodeName;");
eval_r(data_obj + ".childNodes[i].attributes[j].text=obj.childNodes(i).attributes(j).text;");
eval_r(data_obj + ".childNodes[i]._attributes[obj.childNodes(i).attributes(j).nodeName]=j;");
}
var obj_ = obj.childNodes(i);
var data_obj_ = data_obj + ".childNodes[" + i + "]";
_getXml(obj_,data_obj_);
}
}
//调用示例
xml2javascript('message.xml','aaa');
alert(aaa.childNodes[0].childNodes[1].nodeName);
alert(aaa.childNodes[0].childNodes[1].text);
//alert(aaa.childNodes[0].childNodes[1].attributes[0].text);
</SCRIPT>