Skip to content

Instantly share code, notes, and snippets.

@tmlbl
Last active August 29, 2015 14:14
Show Gist options
  • Save tmlbl/80bed27a6091c6023081 to your computer and use it in GitHub Desktop.
Save tmlbl/80bed27a6091c6023081 to your computer and use it in GitHub Desktop.
xmltojs
// My attempt to make David Walsh's xmlToJson function work
// with libxmltojs. This reproduces the document tree but not
// the text inside in each node. There is a lot of data in these
// documents we are not using... I think we should stick to the
// xpath queries.
// Changes XML to JSON
function xmlToJson (xml) {
// Create the return object
var obj = {};
if (xml.childNodes().length > 0) {
xml.childNodes().forEach(function (item) {
var nodeName = item.name();
if (typeof(obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if (typeof(obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
});
} else {
if (obj.text) {
return obj.text();
}
}
return obj;
};
module.exports = xmlToJson;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment