luosheng

从XML到JSON的转换代码

今天写的一段代码,用于将XML的对象/字符串转化成JSON的对象/字符串。
网上有一个这样的代码的,不过那个拼字符串拼出来……满屏的正则表达式,于是也没有细看……而且那个是LGPL的License,用起来还是有顾忌的。
随便写了写。这东西本来就应该封个包静态调用或者弄成单例模式。不过反正现在这样也能用,就无所谓了。

用法:var json = new Xml2Json(xmlObject).parse(containRoot, returnText);
xmlObject可以为xml的对象或者是字符串,containRoot用来表示生成的json中要不要包含根元素,而returnText表示是以文本还是以对象形式返回json。这两个属性默认均为false。

  1var Xml2Json = Class.create();
  2
  3Xml2Json.prototype = {
  4    initialize : function(xmlElem) {
  5        if (typeof(xmlElem) === 'object') {
  6            this.doc = xmlElem;
  7        }
 else if (typeof(xmlElem) === 'string') {
  8            if (window.ActiveXObject) {
  9                this.doc = new ActiveXObject('Microsoft.XMLDOM');
 10                this.doc.async = 'false';
 11                this.doc.loadXML(xmlElem);
 12            }
 else {
 13                this.doc = new DOMParser().parseFromString(xmlElem, 'text/xml');
 14            }

 15        }

 16    }
,
 17
 18    parse : function(containRoot, returnText) {
 19        var root = this.doc.documentElement || this.doc;
 20        var json = this.__parse__(root, {});
 21        var returnValue = {};
 22        if (containRoot)
 23            returnValue[root.nodeName] = json;
 24        else
 25            returnValue = json;
 26        return returnText ? this.convert(returnValue) : returnValue;
 27    }
,
 28
 29    convert : function(jsonObject) {
 30        return this.__convert__(jsonObject, 0);
 31    }
,
 32
 33    __blank__ : function(s) {
 34        var pattern = /^[\s]*$/g;
 35        return pattern.test(s);
 36    }
,
 37
 38    __convert__ : function(jsonObject, level) {
 39        var template;
 40        var i;
 41        var j;
 42
 43        var tabs = '';
 44        for (i = 0;i < level; i++{
 45            tabs += '\t';
 46        }

 47
 48        if (jsonObject instanceof Array) {
 49            template = '[\n';
 50            for (i = 0;i < jsonObject.length - 1; i++{
 51                template += tabs + '\t'
 52                        + this.__convert__(jsonObject[i], level + 1+ ',\n';
 53            }

 54            template += tabs
 55                    + '\t'
 56                    + this.__convert__(jsonObject[jsonObject.length - 1], level
 57                            + 1+ '\n' + tabs + ']';
 58            return template;
 59        }
 else if (typeof(jsonObject) === 'object') {
 60            template = '{';
 61            for (var property in jsonObject) {
 62                template += '\n\t' + tabs + property + ': '
 63                        + this.__convert__(jsonObject[property], level + 1)
 64                        + ',';
 65            }

 66            template = template.substring(0, template.length - 1);
 67            template += '\n' + tabs + '}
';
 68            return template;
 69        }
 else if (typeof(jsonObject) === 'string') {
 70            return '"' + jsonObject + '"';
 71        }
 else {
 72            return jsonObject;
 73        }

 74    }
,
 75
 76    __parse__ : function(elem, obj) {
 77
 78        for (var i = 0;i < elem.attributes.length; i++{
 79            var attr = elem.attributes[i];
 80            obj[attr.name] = attr.value;
 81        }

 82
 83        for (i = 0;i < elem.childNodes.length; i++{
 84            var child = elem.childNodes[i];
 85            var property = child.nodeName;
 86            if (child.nodeType !== Node.TEXT_NODE
 87                    && child.nodeType !== Node.COMMENT_NODE) {
 88                var childObj = this.__parse__(child, {});
 89                if (!obj[property])
 90                    obj[property] = [];
 91                obj[property].push(childObj);
 92            }
 else if (child.nodeType === Node.TEXT_NODE
 93                    && !this.__blank__(child.data)) {
 94                obj['value'] = child.data;
 95            }

 96        }

 97
 98        return this.__reduce__(obj);
 99    }
,
100
101    __reduce__ : function(obj) {
102        var count = 0;
103        for (var property in obj) {
104            var value = obj[property];
105            if (value instanceof Array && value.length === 1{
106                obj[property] = value[0];
107            }

108            count++;
109        }

110        if (count === 1 && obj['value'])
111            obj = obj['value'];
112        return obj;
113    }

114}

posted on 2007-08-23 21:42  罂粟  阅读(745)  评论(0编辑  收藏  举报

导航