Search code examples
javascriptjsonnode.jsxmlxml2js

XML to Json Nodejs


I'm using xml2js npm to parse xml to json and everything goes well except in xml file, there is an attribute key

<ht:approx_traffic>20,000+</ht:approx_traffic>

and xml2js parses it in json like this

"ht:approx_traffic": [
   "20,000+"
]

Is there a way that I can get rid of the colon there? Thanks.

I just simply use this to parse

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

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

Solution

  • Use the stripPrefix processor.

    var stripPrefix = require('xml2js').processors.stripPrefix;
    
    parser.parseString(
      data,
      { tagNameProcessors: [stripPrefix] },
      function(err, result) {
        console.dir(result);
        console.log('Done');
      }
    );
    

    Read the spec here. Working example.