Skip to content

Instantly share code, notes, and snippets.

@hu2di
Created April 10, 2017 02:36
Show Gist options
  • Save hu2di/0e6132f0aafb5d15aea497b34c5cf673 to your computer and use it in GitHub Desktop.
Save hu2di/0e6132f0aafb5d15aea497b34c5cf673 to your computer and use it in GitHub Desktop.
Read XML file into Node.js as a JSON
//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