node-xml2js icon indicating copy to clipboard operation
node-xml2js copied to clipboard

Non-whitespace before first tag in xmls2js

Open kkp2004 opened this issue 10 years ago • 20 comments

Below code i am running and trying to parse XML response through xmls2js,

soapClient.call({ 'method':'findAll', 'params' : { 'maxResults' : 100, 'orderDirection' : 0, 'orderField' : 'creationdate', 'startIndex' :1 } } ) .then(function(res) { console.log(res.response); res.data // response data as array var data=res.response // full response data (including xml) res.header // response header

        parseString(data, function(err, result){
            if(err) console.log(err);
            console.log(result); 
        });
    },
    function(err) {
        console.log(err);
    }
);  

While running the code getting below error.

Error: Non-whitespace before first tag.

kkp2004 avatar Nov 10 '16 18:11 kkp2004

How does the XML you pass in look like?

Leonidas-from-XIV avatar Nov 10 '16 20:11 Leonidas-from-XIV

This blog solved it for me.

fxlemire avatar Dec 05 '16 15:12 fxlemire

This should work out of the box, since xml2js has now code to remove the byte order mark before parsing.

Leonidas-from-XIV avatar Dec 05 '16 16:12 Leonidas-from-XIV

@fxlemire I am facing the same issue and the blog link is not working.

Please provide a solution. Thank you!.

lucifer-AM avatar Jul 14 '17 05:07 lucifer-AM

@lucifer-AM To fix the issue:

var cleanedString = origString.replace("\ufeff", "");

fxlemire avatar Jul 17 '17 13:07 fxlemire

Having same error.

and var cleanedString = origString.replace("\ufeff", ""); didnt work for me.

attached sample xml

xml.txt

lafiza avatar Jul 17 '17 14:07 lafiza

@fxlemire I have a feed Reader that I created for RDF, ATOM as well as RSS. It works fine for all three but for some feeds it give this error. Error: Non-whitespace before first tag. Currently I think it is related to the HTTP response that I am getting after I hit the feed URL. As the response is garbled I can't give it to the xml2js. Currently I am avoiding the erroneous feed urls. Thanks anyways.

lucifer-AM avatar Jul 18 '17 07:07 lucifer-AM

Any fix?

idemax avatar Sep 26 '17 12:09 idemax

I had the same issue, but then I realized I was trying to parse the entire response object of an AJAX request instead of just the response data.

justintemps avatar Oct 16 '17 19:10 justintemps

I have the same issue. Any solutions?

Desireedaccache avatar Oct 25 '17 06:10 Desireedaccache

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

fs.readFile('../storage/epg/epg.xml', function(err, data) { var data = data.toString().replace("\ufeff", ""); parseString(data, function (err, result) { console.dir(result); }); });

gribeiro8 avatar Mar 12 '18 12:03 gribeiro8

XML files are utf8 and when stored as a file should have a binary header ("\ufeff"). The previous comment solve this by removing it before passing it. An alternative is to use fs.readfile which will deal with the header.

fs.readFile('../simple test.xml', function(err, data) {
    var doc = new xmldoc.XmlDocument(data);

beaumsc avatar Apr 08 '18 13:04 beaumsc

Thanks everyone for sharing your solutions and to the authors of this library for creating it! This thread was helpful to me.

In case it helps someone else, here's a full example, going from xml file with binary headers to writing the results to a file.

const fs = require('fs');
const util = require('util')
const parseString = require('xml2js').parseString;
const fileToParse = ('./my-file.xml')
const outputFilename=('output.json')

fs.readFile(fileToParse, function (err, data) {
    parseString(data, function (err, result) {
        console.dir(result);
        if (err) {
            console.log(err)
        }
       // do something with the JS object called result, or see below to save as JSON
        fs.writeFile('output.json', JSON.stringify(result), (writeErr) => {
            if (writeErr) throw writeErr;
            console.log('The file has been saved to ' + outputFilename);
        });
    });
});

If you try to write the JS object straight to a file, you get [Object object] in the file, so I converted to JSON.

jenweber avatar Dec 17 '18 19:12 jenweber

I had the same issue, but then I realized I was trying to parse the entire response object of an AJAX request instead of just the response data.

fk me

voe1999 avatar May 11 '19 10:05 voe1999

I used a try and catch block, worked perfectly for me.

sratemo avatar Apr 23 '20 18:04 sratemo

@justintemps, you just saved me, thank you so much!! haha

ericmadureira avatar May 22 '20 19:05 ericmadureira

Try passing

{
    preserveWhitespace: true
}

In options when instantiating the client.

maurocolella avatar Jul 01 '20 08:07 maurocolella

This may be overkill or an obtuse approach but this did the trick for my https server receiving XML webhooks. This snippet depends on express and I'm using DOMParser from xmldom to clean the data before it is parsed.

app.post("/test", (req, res) => {
  let body = '';
  req.setEncoding('utf8');
  req.on("data", (chunk) => {
    body += chunk;
  });
  req.on('end', () => {
    const tempData = body.toString();
    try {
      const cleanData = new DOMParser().parseFromString(tempData, "text/xml");
      return parseString(cleanData, (err, result) => {
        if (err) {
          console.log(err)
          res.statusCode = 400;
          return res.end("Error 2: " + err)
        } else {
          console.log(result);
          res.statusCode = 200;
          return res.end("Success.");
        }
      });
    } catch (err) {
      console.log(err);
      res.statusCode = 400;
      return res.end("Error 1: " + err);
    }
  });
});

Console:

image

Ngrok inspection:

image

xkllbr avatar Jul 01 '21 19:07 xkllbr

I had the same issue, but then I realized I was trying to parse the entire response object of an AJAX request instead of just the response data.

Same to me, I'm feeling very stupid right now hahahaha Thanks.

gentildpinto avatar Apr 02 '24 12:04 gentildpinto

This blog solved it for me.

this blog no longer exists. Can someone post the solution.

sh977218 avatar Feb 15 '26 19:02 sh977218