Search code examples
javascriptnode.jsxml2js

Issue with parsing using xml2js


I have an xml in which tag name contains colon(:) It looks something like this:

<samlp:Response>
data
</samlp:Response>

I am using following code to parse this xml to json but can't use it because the tag name contains colon.

var xml2js = require('xml2js');
var parser = new xml2js.Parser();
var fs = require('fs');

    fs.readFile(
  filePath,
  function(err,data){
    if(!err){
      parser.parseString(data, function (err, result) {
        //Getting a linter warning/error at this point
        console.log(result.samlp:Response);
      });
    }else{
      callback('error while parsing assertion'+err);
    }
  }
);

};

Error:

events.js:161
      throw er; // Unhandled 'error' event
      ^

TypeError: Cannot read property 'Response' of undefined

How can I parse this XML successfully without changing the contents of my xml?

enter image description here


Solution

  • xml2js allows you to explicity set XML namespace removal by adding the stripPrefix to the tagNameProcessors array in your config options.

    const xml2js = require('xml2js')
    const processors = xml2js.processors
    const xmlParser = xml2js.Parser({
      tagNameProcessors: [processors.stripPrefix]
    })
    const fs = require('fs')
    
    fs.readFile(filepath, 'utf8', (err, data) => {
      if (err) {
        //handle error
        console.log(err)
      } else {
        xmlParser.parseString(data, (err, result) => {
          if (err) {
            // handle error    
            console.log(err) 
          } else {
            console.log(result)
          }
        })  
      }
    })