Reading XML file in Node.js
Solution 1:
use xml2json
https://www.npmjs.com/package/xml2json
fs = require('fs');
var parser = require('xml2json');
fs.readFile( './data.xml', function(err, data) {
var json = parser.toJson(data);
console.log("to json ->", json);
});
Solution 2:
From the documentation.
The callback is passed two arguments (err, data), where data is the contents of the file.
If no encoding is specified, then the raw buffer is returned.
If options is a string, then it specifies the encoding. Example:
fs.readFile('/etc/passwd', 'utf8', callback);
You didn't specify an encoding, so you get the raw buffer.
Solution 3:
@Sandburg mentioned xml-js
in a comment and it worked best for me (several years after this question was asked). The others I tried were: xml2json
which required some Windows Sdk that I did not want to deal with, and xml2js
that did not provide an easy enough OTB way to search through attributes.
I had to pull out a specific attribute in an xml file 3 nodes deep and xml-js
did it with ease.
https://www.npmjs.com/package/xml-js
With the following example file stats.xml
<stats>
<runs>
<latest date="2019-12-12" success="100" fail="2" />
<latest date="2019-12-11" success="99" fail="3" />
<latest date="2019-12-10" success="102" fail="0" />
<latest date="2019-12-09" success="102" fail="0" />
</runs>
</stats>
I used xml-js
to find the element /stats/runs/latest
with attribute @date='2019-12-12'
like so
const convert = require('xml-js');
const fs = require('fs');
// read file
const xmlFile = fs.readFileSync('stats.xml', 'utf8');
// parse xml file as a json object
const jsonData = JSON.parse(convert.xml2json(xmlFile, {compact: true, spaces: 2}));
const targetNode =
// element '/stats/runs/latest'
jsonData.stats.runs.latest
.find(x =>
// attribute '@date'
x._attributes.date === '2019-12-12'
);
// targetNode has the 'latest' node we want
// now output the 'fail' attribute from that node
console.log(targetNode._attributes.fail); // outputs: 2
Solution 4:
fs.readFile has an optional second parameter: encoding. If you do not include this parameter it will automatically return you a Buffer object.
https://nodejs.org/api/fs.html#fs_fs_readfile_filename_options_callback
If you know the encoding just use:
fs.readFile(__dirname + '/../public/sitemap.xml', 'utf8', function(err, data) {
if (!err) {
console.log(data);
}
});