WRT中使用JS自动将XML、JSON转换成为对象
由于经常接触WRT,所以写了个一个解析XML和JSON的代码,比较通用。
解析XML的是很,代码会根据相关的配置,将节点组合成对象,然后返回。
?
请看代码:
NetWorkUtils.js - 用于Ajax网络连接
?
?
/** * 抓取网络数据,并进行处理 * @param url 数据的url * @param param 需要传递的参数 * @param callback 处理数据的函数 * @param exceptionCallBack 出现异常如何处理的函数 * @param isXML 是否是xml格式的数据,true 或者是false * @return */function ajaxFetch(url, param, callback,exceptionCallBack, isXML) {var req = new Ajax();req.onreadystatechange = function() {if (req.readyState == 4 && req.status == 200) {if (!isXML && req.responseText != null) {callback(req.responseText);} else if (isXML && req.responseXML != null) {callback(req.responseXML);} else {callback(null);}} else if (req.readyState == 4 && req.status != 200) {if(exceptionCallBack!=null&&exceptionCallBack!=undefined)exceptionCallBack();}}var fullURL = url;if (fullURL.indexOf("?") == -1) {fullURL += "?";} else {fullURL += "&";}fullURL += "timestamp=" + (new Date().getTime());fullURL += "&" + param;req.open("GET", fullURL, true);req.send(null);}
?
?
?
ProcessData.js - 用于处理数据并且进行回调
?
?
/** * 构造方法 * @param {Object} Url xml JSON地址 * @param {Object} parentNode 父节点,比如要把<item><title>aaa</title></item>转成对象,此参数就是item * @param {Object} options * @param {Object} processDataFunction 象完成后需要用的方法 */function ProcessData(Url, parentNode, options, processDataFunction){ this.URL = xmlUrl; this.parentNode = parentNode; this.options = options; this.processDataFunction = processDataFunction; selfProcessData = this;}ProcessData.prototype = new Object();ProcessData.prototype.URL;ProcessData.prototype.options;ProcessData.prototype.parentNode;ProcessData.prototype.processDataFunction;ProcessData.prototype.dataArray;/** * 处理XML数据调用的方法 * @param {Object} exceptionFunction 抓取数据时候发生异常需要做的事情,比如提示重新连接等等 */ProcessData.prototype.buildxml = function(exceptionFunction){ ajaxFetch(selfProcessData.URL, null, selfProcessData.buildXMLCallBack, exceptionFunction, true);}/** * 处理JSON数据调用的方法 * @param {Object} exceptionFunction 抓取数据时候发生异常需要做的事情,比如提示重新连接等等 */ProcessData.prototype.buildJSON = function(exceptionFunction){ ajaxFetch(selfProcessData.URL, null, selfProcessData.buildJSONCallBack, exceptionFunction, false);}/** * 抓取JSON后回调方法 * @param {string} JSON字符串 */ProcessData.prototype.buildJSONCallBack = function(data){ if (data == null && data == undefined) { return null; }json = stringToJSON(data);selfProcessData.processDataFunction(json);}/** * 抓取xml后回调方法 * @param {Object} data dom 文档 */ProcessData.prototype.buildXMLCallBack = function(data){ if (data == null && data == undefined) { return null; } var items = data.documentElement.getElementsByTagName(selfProcessData.parentNode); if (items == null && items == undefined) { return null; } var dataLength = items.length; var array = []; for (var i = 0; i < dataLength; i++) { //Set property and data into object selfProcessData.data1 = new Data(); var optionsLength = selfProcessData.options.length; for (var j = 0; j < optionsLength; j++) { var option = selfProcessData.options[j]; //要从XML读取的节点名称 var nodeName = option['nodeName']; //取得节点元素 var da = items[i].getElementsByTagName(nodeName)[0]; //通过options取得对应的成员变量名称 var memberName = option['memberName']; var nodeValueOrAttribute = option['nodeValueOrAttribute']; var attributeName = option['attributeName']; if (da != null || da != undefined) { //判断是取节点的值还是其中的属性值 if (nodeValueOrAttribute == 'attribute' && (attributeName != undefined || attributeName != null)) { selfProcessData.data1.putProperty(memberName, da.getAttribute(attributeName)); } else { if (da.firstChild == null || da.firstChild == undefined) { selfProcessData.data1.putProperty(memberName, null); } else { selfProcessData.data1.putProperty(memberName, da.firstChild.nodeValue); } } } else { selfProcessData.data1.putProperty(memberName, null); } } array[i] = selfProcessData.data1; } selfProcessData.processDataFunction(array);}?
?
?
json2.js - 用于处理JSON数据
?
?
/** * 将JSON转换成为string对象 */jsonToString = function(obj){ var THIS = this; switch(typeof(obj)){ case 'string': return '"' + obj.replace(/(["\\])/g, '\\$1') + '"'; case 'array': return '[' + obj.map(THIS.jsonToString).join(',') + ']'; case 'object': if(obj instanceof Array){ var strArr = []; var len = obj.length; for(var i=0; i<len; i++){ strArr.push(THIS.jsonToString(obj[i])); } return '[' + strArr.join(',') + ']'; }else if(obj==null){ return 'null'; }else{ var string = []; for (var property in obj) string.push(THIS.jsonToString(property) + ':' + THIS.jsonToString(obj[property])); return '{' + string.join(',') + '}'; } case 'number': return obj; case false: return obj; } }/** * 将String转换成JSON对象 */stringToJSON = function(obj){ return eval('(' + obj + ')');}?
?
?
Data.js - XML解析完成节点对象模型
?
?
function Data() {var argLength =arguments.length;}/** * Data继承于Object */Data.prototype = new Object();/** * 为Data增加成员变量,此类将会增加一个变量 * @param property 属性的名称 * @param value 属性的值 * */Data.prototype.putProperty = function(property, value) {var s = new String(value);eval("this." + property + "=s.toString();");}/** * 增加一个函数 * @param functionName 函数的名称 * @param functionValue 函数的执行体 * */Data.prototype.putFunction = function(functionName, functionValue) {eval("this." + functionName + "=" + functionValue);}?
?
?
使用时候的代码 :
?
?
var e = "http://mdev.cc/dev/rss.php?fid=3"; var options1 = [{ nodeName: 'guid',//节点名称 memberName: 'isPermaLink',//数据放在对象中的成员变量名称 nodeValueOrAttribute: 'attribute',//是取属性的值还是取元素的文本?attribute:取得属性值,nodeValue:取得节点值 attributeName: 'isPermaLink'//取哪个属性? }, { nodeName: 'description',//节点名称 memberName: 'description', nodeValueOrAttribute: 'nodeValue' }, { nodeName: 'guid',//节点名称 memberName: 'guidValue', nodeValueOrAttribute: 'nodeValue' }]; var options2 = [{ nodeName: 'title',//节点名称 memberName: 'title',//数据放在对象中的成员变量名称 nodeValueOrAttribute: 'nodeValue',//attribute:取得属性值,nodeValue:取得节点值 }, { nodeName: 'description',//节点名称 memberName: 'description', nodeValueOrAttribute: 'nodeValue' }, { nodeName: 'link',//节点名称 memberName: 'link', nodeValueOrAttribute: 'nodeValue' }, { nodeName: 'author',//节点名称 memberName: 'author', nodeValueOrAttribute: 'nodeValue' }, { nodeName: 'category',//节点名称 memberName: 'category', nodeValueOrAttribute: 'nodeValue' }]; /* processData = new ProcessData(e, "item",options2 , function(data){ //alert(data.length); alert(data[0].title +" "+data[0].category +" "+data[0].description); }); processData.buildxml(); //这里要传递一个异常处理函数,当网络有问题的时候会自动调用 */ /////JSON var sss = "http://json.com/brands.txt"; processData = new ProcessData(sss, "item", options2, function(json){ alert(json.brands[1].brand); }); processData.buildJSON();//这里要传递一个异常处理函数,当网络有问题的时候会自动调用?
?
?processData.buildxml();
?processData.buildJSON();
?
这两个函数表示开始解析XML 或者JSON,如果在WRT中最后传递异常处理函数,不然出现了网络异常,程序在手机上就
不会跑了,实例:
?
processData.buildxml(function(){alert("No network!");});?
这些代码在NOKIA N97 6710 E72机器上跑都没问题的,其他的机器没有测试,应该不会有多大问题。
?
?
1 楼 abin7230 2010-03-26 我目前刚开始学弄WRT,谢谢你的资料!有时间指点下呀