Read write XML node values in "NodeJs"

Udy Warnasuriya picture Udy Warnasuriya · Oct 18, 2012 · Viewed 9.1k times · Source

Can anyone guide me with how to read/ write XML nodevalues parsed by xml2js.Parser() in 'NodeJS'? So far my code is as flows:

var parser = new xml2js.Parser();
fs.readFile( './foo.xml', function(err, data) {
    parser.parseString(data, function (err, result) {
        console.dir(result);
    });
});

I want to read the values of result as follows

result.to

my XML:

<note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
</note>

Answer

thisisnotadisplayname picture thisisnotadisplayname · Oct 18, 2012

I think that you have to check the value of result.note.to[0] :

xml2js = require('xml2js');
fs = require('fs');

var parser = new xml2js.Parser();
fs.readFile( './foo.xml', function(err, data) {
    parser.parseString(data, function (err, result) {
        console.dir(result.note.to[0]);
    });
});