Search code examples
node.jsreadxml

Read write XML node values in "NodeJs"


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>

Solution

  • 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]);
        });
    });