Skip to content

Instantly share code, notes, and snippets.

@mediaupstream
Created December 19, 2011 06:57
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mediaupstream/1495793 to your computer and use it in GitHub Desktop.
Save mediaupstream/1495793 to your computer and use it in GitHub Desktop.
json2xml - Convert an xml2js JSON object back to XML
/**
* 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!
};
@evantahler
Copy link

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!

@mediaupstream
Copy link
Author

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

@evantahler
Copy link

It seems there might already be one: https://github.com/appsattic/node-data2xml

@Redsandro
Copy link

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