Reading a portion of the file defined by 2 end points in nodejs

41 views Asked by At

I am a newbie on nodeJs, but i am loving it already. I have the following data.xml file.

<data>
 <student>
  <age>16</age>
  <name>Bill</name>
 </student>
 <teacher>
  <age>33</age>
  <name>Priyanka</name>
 </teacher>
</data>

I want to read the details of the student from this file. I explored fs.readStream, fs.readFile but some how not being able to get it right. Readline might be a solution(i am not sure), but what if the xml is not formatted well?

Thanks in advance.

1

There are 1 answers

2
Rayee Roded On BEST ANSWER

You can't parse invalid xml- so fix it. Then you can use xml2js (install by running npm install xml2js) node module and this code:

var fs= require('fs');
var parseString = require('xml2js').parseString;

fs.readFile('./data.xml', 'utf8', function read(err, data) {
    if (err) {
        throw err;
    }

    parseString(data, {trim: true}, function (err, result) {
        if (err){
            throw err;
        }
        console.dir(result);
    });
});

If you won't fix the xml, the code will throw an exception of course (closing tag of teacher's age is invalid). You should check the encoding of your xml file,for brevity I assumed utf8.