【问题标题】:Cannot access json values after converting from xml using xml-js parser使用 xml-js 解析器从 xml 转换后无法访问 json 值
【发布时间】:2019-11-07 22:19:08
【问题描述】:

我使用以下代码解析 xml

var convert = require('xml-js');
var xml = require('fs').readFileSync('./2B2DE7DD-FD11-4F2C-AF0D-A244E5977CBA.xml', 'utf8');
result = convert.xml2json(xml, { spaces: 4});

结果抛出以下 JSON

{
    "declaration": {
        "attributes": {
            "version": "1.0",
            "encoding": "utf-8"
        }
    }
}

但是,如果我尝试使用result["declaration"]访问“声明”,控制台将返回undefined

我应该使用另一个解析器还是获取值有问题。

【问题讨论】:

    标签: node.js json xml


    【解决方案1】:

    如果您希望它返回对象,请使用xml2js 而不是xml2json

    result = convert.xml2js(xml, options);    // to convert xml text to javascript object
    result = convert.xml2json(xml, options);  // to convert xml text to json text
    

    【讨论】:

      【解决方案2】:

      result 的数据类型是 String,不是 JavaScript 对象。也就是说,convert.xml2json(xml, { spaces: 4}); 语句将返回一个 JSON 字符串,而不是 JS 对象。

      要访问declaration,需要将JSON字符串解析为对象:

      var convert = require('xml-js');
      var xml = require('fs').readFileSync('./2B2DE7DD-FD11-4F2C-AF0D-A244E5977CBA.xml', 'utf8');
      result = convert.xml2json(xml, { spaces: 4});
      
      result = JSON.parse(result);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-14
        • 1970-01-01
        • 1970-01-01
        • 2015-07-28
        • 1970-01-01
        • 2018-06-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多