问题与parsing使用xml2js
我有一个XML标签名称包含冒号(:)它看起来像这样:
<samlp:Response> data </samlp:Response>
我正在使用下面的代码来parsing这个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的内容的情况下成功parsing此XML?
xml2js
允许你通过在configuration选项中将tagNameProcessors
添加到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) } }) } })