Skip to content

Instantly share code, notes, and snippets.

@devhawk
Created May 3, 2012 23:02
Show Gist options
  • Save devhawk/2590217 to your computer and use it in GitHub Desktop.
Save devhawk/2590217 to your computer and use it in GitHub Desktop.
simple utility function to convert XML to JSON using TreeWalker
function XML2JSON(doc) {
function workhorse(tw) {
var curNode = tw.currentNode;
if (curNode.nodeType === 3) {
return curNode.nodeValue;
}
var obj = {}
if (!!curNode.attributes) {
for (var x = 0; x < curNode.attributes.length; x++) {
var a = curNode.attributes.item(x);
obj["$" + a.nodeName] = a.nodeValue;
}
}
var child = tw.firstChild();
var backup = child !== null;
while (!!child) {
var name = child.nodeName;
var value = workhorse(tw);
if (!obj[name]) {
obj[name] = value;
} else if (Array.isArray(obj[name])) {
obj[name].push(value);
} else {
var temp = obj[name];
obj[name] = [temp, value];
}
child = tw.nextSibling();
}
if (backup) { tw.parentNode(); }
return obj;
}
var tw = document.createTreeWalker(doc, NodeFilter.SHOW_ELEMENT + NodeFilter.SHOW_TEXT, function (node) {
if (node.nodeType === 3 && node.nodeValue.trim().length === 0) {
return NodeFilter.FILTER_SKIP;
}
return NodeFilter.FILTER_ACCEPT;
}, false);
return workhorse(tw);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment