【问题标题】:Issue with parsing using xml2js使用 xml2js 解析的问题
【发布时间】:2017-09-04 20:13:36
【问题描述】:

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

【问题讨论】:

  • 在回调中添加if (err)以查看实际错误
  • @MariaInesParnisari 请看截图,parseString 没有被调用,因为它是一个语法错误。

标签: javascript node.js xml2js


【解决方案1】:

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)
      }
    })  
  }
})

【讨论】:

    【解决方案2】:

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

    object['property']
    

    在你的情况下

    result['samlp:Response']
    

    【讨论】:

      猜你喜欢
      • 2014-08-30
      • 2019-03-15
      • 2012-06-09
      • 2019-10-24
      • 1970-01-01
      • 2018-10-31
      • 1970-01-01
      • 2016-06-15
      • 1970-01-01
      相关资源
      最近更新 更多