You can try:
var path = 'testxml.xml';
var fs = require('fs');
var xml2js = require('xml2js');
var parser = new xml2js.Parser();
var xml = fs.readFileSync(path);
parser.parseString(xml, function (err, result) {
if (err) {
console.error('xml2js.parseString: Error occurred: ', err);
} else {
console.log(JSON.stringify(result, null, 2));
console.log('AlarmCode: ', result.QCapsule.AlarmLog[0].AlarmLogItem[0].AlarmCode[0]);
}
});
Change the code like so and you don't need those annoying [0] array indexing operators.
var path = 'testxml.xml';
var fs = require('fs');
var xml2js = require('xml2js');
var parser = new xml2js.Parser({explicitArray: false});
var xml = fs.readFileSync(path);
parser.parseString(xml, function (err, result) {
if (err) {
console.error('xml2js.parseString: Error occurred: ', err);
} else {
console.log(JSON.stringify(result, null, 2));
console.log('AlarmCode: ', result.QCapsule.AlarmLog.AlarmLogItem[0].AlarmCode);
}
});
Bear in mind of course that if you do have multiple child elements in the XML data, you'll need to use the indexing operator.
There are some other useful options in the Options section of the xml2js.
And I think xml2js is a pretty nice XML parser, it does a lot!
I tested with Xml that looks like this:
<QCapsule id="1" name="ALARMS">
<AlarmLog itemCount="2">
<AlarmLogItem listIndex="0">
<EntryType>1</EntryType>
<AlarmCode>180</AlarmCode>
</AlarmLogItem>
<AlarmLogItem listIndex="1">
<EntryType>1</EntryType>
<AlarmCode>101</AlarmCode>
</AlarmLogItem>
</AlarmLog>
</QCapsule>
Also useful to have a print all alarms function:
var printAllAlarms = function(alarmLogItems) {
console.log(`PrintAllAlarms: Total alarm(s): ${alarmLogItems.length}`);
alarmLogItems.forEach((alarmLog) => { ;
console.log(`AlarmLogItem: EntryType: ${alarmLog.EntryType} AlarmCode: ${alarmLog.AlarmCode}`);
});
}
printAllAlarms(result.QCapsule.AlarmLog.AlarmLogItem);