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?
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?
Share Improve this question edited Apr 10, 2017 at 0:01 java_doctor_101 asked Apr 9, 2017 at 21:22 java_doctor_101java_doctor_101 3,3676 gold badges50 silver badges82 bronze badges 2-
Add
if (err)
inside the callback to see the actual error – Maria Ines Parnisari Commented Apr 9, 2017 at 21:24 - @MariaInesParnisari Please see the screenshot, parseString is not getting called since it's a syntaxe error. – java_doctor_101 Commented Apr 9, 2017 at 21:35
2 Answers
Reset to default 5xml2js
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)
}
})
}
})
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']
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745249887a4618613.html
评论列表(0条)