Created
December 19, 2011 06:57
-
-
Save mediaupstream/1495793 to your computer and use it in GitHub Desktop.
json2xml - Convert an xml2js JSON object back to XML
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
/** | |
* json2xml - Convert an xml2js JSON object back to XML | |
* | |
* @author Derek Anderson | |
* @copyright 2011 Media Upstream | |
* @license MIT License | |
* | |
* Usage: | |
* | |
* json2xml({"Foo": "@": { "baz": "bar", "production":"true" }}, "Test", function(xml){ | |
* console.log(xml); // log the XML data | |
* }); | |
* | |
*/ | |
var json2xml = function(json, root, cb){ | |
var recursion = 0; | |
var xml = '<?xml version="1.0" ?>'; | |
var isArray = function(obj) { return obj.constructor == Array; }; | |
var parseAttributes = function(node){ | |
for(key in node){ | |
var value = node[key]; | |
xml += ' ' + key +'="'+ value +'"'; | |
}; | |
xml += '>'; | |
}; | |
var parseNode = function(node, parentNode){ | |
recursion++; | |
// Handle Object structures in the JSON properly | |
if(!isArray(node)){ | |
xml += '<'+ parentNode; | |
if(typeof node == 'object' && node['@']){ | |
parseAttributes(node['@']); | |
} else { | |
xml += '>'; | |
} | |
for(key in node){ | |
var value = node[key]; | |
// text values | |
if(typeof value == 'string'){ | |
if(key === '#'){ | |
xml += value; | |
} else { | |
xml += '<'+ key +'>'+ value + '</'+key+'>'; | |
} | |
} | |
// is an object | |
if(typeof value == 'object' && key != '@'){ | |
parseNode(node[key], key); | |
} | |
} | |
recursion--; | |
xml += '</'+ parentNode +'>'; | |
} | |
// Handle array structures in the JSON properly | |
if(isArray(node)){ | |
for(var i=0; i < node.length; i++){ | |
parseNode(node[i], parentNode); | |
} | |
recursion--; | |
} | |
if (recursion === 0) { cb(xml); } | |
}; | |
parseNode(json, root); // fire up the parser! | |
}; |
Going from JSON to XML, assuming you don't care about XML attributes and the like, should be pretty straight forward. Maybe we should start a new NPM package for plain JSON to XML
It seems there might already be one: https://github.com/appsattic/node-data2xml
Yes, but this one uses compatible @ and # keys for respectively attributes and text-nodes, and the one linked uses _attr and _value.
Nice script!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! I'm looking to render XML from the actionHero framework.
I can't seem to find an NPM package which does json->XML, but this will do!