[英]Issue with parsing using xml2js
I have an xml in which tag name contains colon(:) It looks something like this:我有一个 xml,其中标记名称包含冒号 (:) 它看起来像这样:
<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.我正在使用以下代码将此 xml 解析为 json,但无法使用它,因为标记名称包含冒号。
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?如何在不更改 xml 内容的情况下成功解析此 XML?
xml2js
allows you to explicity set XML namespace removal by adding the stripPrefix
to the tagNameProcessors
array in your config options . xml2js
允许您通过将stripPrefix
添加到配置选项中的tagNameProcessors
数组来显式设置 XML 命名空间删除。
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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.