Skip to content

Instantly share code, notes, and snippets.

@dolmen
Created August 25, 2010 16:14
Show Gist options
  • Save dolmen/549788 to your computer and use it in GitHub Desktop.
Save dolmen/549788 to your computer and use it in GitHub Desktop.
JSON to XML serializer
// 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('&', '&amp;').replace('"', '&quot;'), '"');
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('&', '&amp;').replace('<', '&lt;'));
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('&', '&amp;').replace('<', '&lt;'), "</", 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