Created
April 10, 2017 02:36
-
-
Save hu2di/0e6132f0aafb5d15aea497b34c5cf673 to your computer and use it in GitHub Desktop.
Read XML file into Node.js as a JSON
This file contains 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
//nstallation: | |
//npm install --save xml2js | |
//Usage: | |
//Read XML | |
var returnJSONResults = function(baseName, queryName) { | |
var XMLPath = "data.xml"; | |
var rawJSON = loadXMLDoc(XMLPath); | |
function loadXMLDoc(filePath) { | |
var fs = require('fs'); | |
var xml2js = require('xml2js'); | |
var json; | |
try { | |
var fileData = fs.readFileSync(filePath, 'ascii'); | |
var parser = new xml2js.Parser(); | |
parser.parseString(fileData.substring(0, fileData.length), function (err, result) { | |
json = JSON.stringify(result); | |
console.log(JSON.stringify(result)); | |
}); | |
console.log("File '" + filePath + "/ was successfully read.\n"); | |
return json; | |
} catch (ex) { | |
console.log(ex) | |
} | |
} | |
}(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment