- 作者:zhaozj
- 发表时间:2020-12-23 10:53
- 来源:未知
<SCRIPT LANGUAGE="JavaScript"> /** * 递归法读xml所有数据(包括属性值)放入数组 * */ 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(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(data_obj + ".childNodes=new Array();");eval(data_obj + "._childNodes=new Array();");for (var i=0; i<node_count; i++) {if (obj.childNodes(i).nodeName == '#text') {eval(data_obj + ".text=obj.text;"); //元素名称return;}if (obj.childNodes(i).nodeName == '#cdata-section') {eval(data_obj + ".text= obj.text;");return;}eval(data_obj + ".childNodes[i]=new Object();"); //新建一个元素eval(data_obj + ".childNodes[i].nodeName=obj.childNodes(i).nodeName;"); //元素名称eval(data_obj + "._childNodes[obj.childNodes(i).nodeName]=i;"); //元素缓存
//属性var attribute_count = obj.childNodes(i).attributes.length;eval(data_obj + ".childNodes[i].attributes=new Array();"); //属性数组eval(data_obj + ".childNodes[i]._attributes=new Array();"); //属性缓存数组for (var j=0; j<attribute_count; j++) {eval(data_obj + ".childNodes[i].attributes[j]=new Object();");eval(data_obj + ".childNodes[i].attributes[j].nodeName=obj.childNodes(i).attributes(j).nodeName;");eval(data_obj + ".childNodes[i].attributes[j].text=obj.childNodes(i).attributes(j).text;");eval(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('Config.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>
<script language=JavaScript> /** * 递归法读xml所有数据(包括属性值)放入数组 * */ 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(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(data_obj + ".childNodes=new Array();"); eval(data_obj + "._childNodes=new Array();"); for (var i=0; i