使用xml2js解析的问题

时间:2017-04-09 21:22:49

标签: javascript node.js xml2js

我有一个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?

enter image description here

2 个答案:

答案 0 :(得分:3)

xml2js允许您通过添加stripPrefix to the tagNameProcessors array in your config options来明确设置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)
      }
    })  
  }
})

答案 1 :(得分:0)

我喜欢接受的答案,但请记住,您可以使用其键访问属性。

object['property']

所以在你的情况下

result['samlp:Response']
相关问题