xml to object

/*
convert xml or string to object
2012.02.24
by Anjey wu
*/
(function(){
var xmlHelper = {tobject:tobject};
function tobject(x){
x = getType(x) === "xmldocument"? x:toxml(x);
var n = x.documentElement;
var o = xml2object(n, true);
return o;
}
function toxml(s){
if(s.indexOf("<?xml") != 0) s = '<?xml version="1.0" encoding="utf-8"?>' + s;
var x = new DOMParser().parseFromString(s, "text/xml");
return x;
}
function xml2object(n, de){
if(!de && !n.length) return {};
n = de? [n]:n;
var o = {}, c = null;
for(var i=0,l=n.length; i<l; i++){
if(getType(n[i]) === "text"){
if(l == 1 && trim(n[0].nodeValue)) o.value = n[0].nodeValue;
continue;
}
c = mix(getAttr(n[i]), xml2object(n[i].childNodes));
o[n[i].nodeName] = makeValue(o[n[i].nodeName], c);
}
return o?o:{};
}
function getAttr(node){
var ob = {};
for(var i = 0,n; n=node.attributes[i++];)
ob[n.nodeName] = n.nodeValue;
return ob;
}
function getType(o){
return Object.prototype.toString.apply(o).match(/\w+/g)[1].toLowerCase();
}
function trim(s){
return s.replace(/^\s+|\s+$/,"");
}
function makeValue(v1,v2){
if(v1){
if(getType(v1) === "array") v1.push(v2);
else v1 = [v1,v2];
return v1;
}else return v2;
}
function mix(t, s){
var a = [].slice.call(arguments),k,
ride = getType(a[a.length - 1])==="boolean" ? a.pop() : true;
t = t || {};
for(var i = 1;s = a[i++];){
for (k in s) {
if (ride || !(k in t)) {
t[k] = s[k];
}
}
}
return t;
}

window.xmlHelper = xmlHelper;
})();
posted @ 2012-02-24 15:47  Anjey  阅读(571)  评论(0编辑  收藏  举报