Created
August 25, 2010 16:14
-
-
Save dolmen/549788 to your computer and use it in GitHub Desktop.
JSON to XML serializer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A serialization of a JavaScript object to XML | |
// TODO: test suite | |
function json2xml(o, tab) { | |
var xml=[], addChild = function(name, v, ind) { | |
var childs; | |
if (v instanceof Array) { | |
for (var i=0, n=v.length; i<n; i++) | |
addChild(name, v[i], ind); | |
} else if (typeof(v) == "object") { | |
xml.push(ind, "<", name); | |
childs = []; | |
for (var p in v) { | |
if (!v.hasOwnProperty(p)) | |
continue; | |
if (p.charAt(0) == "@") | |
xml.push(" ", p.substr(1), '="', v[p].toString().replace('&', '&').replace('"', '"'), '"'); | |
else | |
childs.push(p); | |
} | |
xml.push( childs.length ? ">" : "/>" ); | |
if (childs.length) { | |
for (var i=0, n=childs.length, p; i<n; i++) { | |
p = childs[i]; | |
if (p == "#text") | |
xml.push(v[p].toString().replace('&', '&').replace('<', '<')); | |
else if (p == "#cdata") | |
xml.push('<![CDATA[', v[p].toString().replace(']]'+'>', ']]]]'+'><![CDATA[>'), ']]'+'>'); | |
else | |
addChild(p, v[p], ind+tab); | |
} | |
if (/[>\n]$/.test(xml[xml.length-1])) | |
xml.push(ind); | |
xml.push('</', name, '>'); | |
} | |
} else { | |
xml.push(ind, "<", name, ">", v.toString().replace('&', '&').replace('<', '<'), "</", name, ">"); | |
} | |
}; | |
for (var m in o) | |
addChild(m, o[m], "\n"); | |
xml.shift(); // Remove the first indent | |
return xml.join(''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment