2

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

java_doctor_101
  • 3,287
  • 4
  • 46
  • 78

2 Answers2

5

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)
      }
    })  
  }
})
peteb
  • 18,552
  • 9
  • 50
  • 62
0

I like the accepted answer but keep in mind that you can access a property using its key.

object['property']

so in your case

result['samlp:Response']
jacstrong
  • 191
  • 2
  • 11