Created
January 3, 2016 13:45
-
-
Save brian-lim-42/d4b4e09370010fbad968 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function createXML(json, rootName) { | |
var doc = document.implementation.createDocument(null, null, null); | |
var rootNode = doc.createElement(rootName); | |
var xml = createXMLRecursive(doc, rootNode, json); | |
return doc.appendChild(xml); | |
} | |
function createXMLRecursive(doc, node, json) { | |
for (var literal in json) { | |
// for string literals | |
if (typeof json[literal] === 'string' && literal !== '$class') { | |
var innerNode = doc.createElement(literal); | |
var text = doc.createTextNode(json[literal]); | |
innerNode.appendChild(text); | |
node.appendChild(innerNode); | |
} | |
// for arrays | |
else if (Object.prototype.toString.call(json[literal]) === '[object Array]') { | |
var nodeList = doc.createElement(literal); | |
for (var i = 0; i < json[literal].length; i++) { | |
// get the class name | |
if (typeof json[literal][i] == 'object' && json[literal][i].hasOwnProperty('$class')) { | |
var className = json[literal][i]['$class']; | |
} | |
else { | |
var className = i; | |
} | |
// create node | |
var innerNode = doc.createElement(className); | |
node.appendChild(createXMLRecursive(doc, innerNode, json[literal][i])); | |
// add node | |
nodeList.appendChild(innerNode); | |
} | |
node.appendChild(nodeList); | |
} | |
// for objects | |
else if (typeof json[literal] === 'object') { | |
createXMLRecursive(doc, node, json[literal]); | |
} | |
} | |
return node; | |
} | |
var obj = { | |
"testxml": { | |
"name": "Brian", | |
"job": "Developer", | |
"david": [ | |
{ | |
"$class": "ClassA", | |
"name": "David", | |
"job": "Developer" | |
} | |
], | |
"chickenList": [ | |
{ | |
"$class": "ClassB", | |
"chicken": "thigh", | |
"made": "made in canada" | |
}, | |
{ | |
"$class": "ClassB", | |
"chicken": "thigh", | |
"made": "made in canada" | |
} | |
], | |
"$class": "ClassA" | |
} | |
} | |
/* | |
var obj = { | |
root: { | |
prop1: { | |
child: "text1", | |
child2: "text2", | |
childobj: [{ | |
childobj1: "childobj1", | |
childobj2: "childobj2" | |
}] | |
}, | |
prop2: { | |
child3: "text3", | |
child4: "text4" | |
} | |
} | |
}; | |
*/ | |
console.log(new XMLSerializer().serializeToString(createXML(obj, 'testxml'))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment