Last active
August 29, 2015 14:14
-
-
Save tmlbl/80bed27a6091c6023081 to your computer and use it in GitHub Desktop.
xmltojs
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
// 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