我有一个 xml,其中标记名称包含冒号 (:) 它看起来像这样:
<samlp:Response>
data
</samlp:Response>
我正在使用以下代码将此 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);
}
}
);
};
错误:
events.js:161
throw er; // Unhandled 'error' event
^
TypeError: Cannot read property 'Response' of undefined
如何在不更改 xml 内容的情况下成功解析此 XML?
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)
}
})
}
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句