简体   繁体   中英

Node xml2js is returning 'undefined' when using parseString()

I'm using this package elsewhere and it's working just fine, however in one particular example with one XML file I'm getting "undefined" errors.

Example:

fs.readFile('./XML/theXMLfile13mb.xml', 'ascii', function(err,data){
    if(err) {
        console.log("Could not open file " + err);
        process.exit(1);
    }

    parseString(data, function (err, result) {
        console.log(result); // Returns undefined
        var json1 = JSON.stringify(result); // Gives an error
        var json = JSON.parse(json1);

The xml2js docs don't really mention how this might be possible/what this might mean. I've tried using other XML files and they work fine. This particular XML file is no bigger than the others nor does it appear to be any less in-tact (it opens fine in my browser and all the data is presented as expected).

Any ideas on how I could troubleshoot this?

You need to convert the data from a Buffer to a String, use this:

parseString(data.toString(), function (err, result) {

Instead of:

parseString(data, function (err, result) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM