0

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');
    });
});
6
  • so you want approx_traffic? Commented Aug 12, 2018 at 10:56
  • You want to get rid of the colon? That would mean that the JSON and the XML differ key-wise. Commented Aug 12, 2018 at 10:56
  • yeah. But I can't seem to figure out Commented Aug 12, 2018 at 10:59
  • 3
    There's a potential option in the xml2js library: stripPrefix: strips the xml namespace prefix. E.g <foo:Bar/> will become 'Bar'. (N.B.: the xmlns prefix is NOT stripped.) see https://www.npmjs.com/package/xml2js#processing-attribute-tag-names-and-values. Commented Aug 12, 2018 at 10:59
  • 1
    answer to your deleted question can be found here nsdateformatter.com Commented Aug 12, 2018 at 14:48

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Some how, I received this error ReferenceError: processors is not defined
Got it fixed. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.