【问题标题】:Parse XML response from api to JSON [duplicate]将 XML 响应从 api 解析为 JSON [重复]
【发布时间】:2019-01-17 20:58:51
【问题描述】:

如何以角度解析我的 XML 响应到 JSON。

这是我的回答:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/"><?xml version="1.0" encoding="utf-8"?&gt;
&lt;FeratelDsiRS xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Status="0" Message="OK" xmlns="XXXXX"&gt;
  &lt;Result Index="1"&gt;
    &lt;Events&gt;
.....
    &lt;/Events&gt;
  &lt;/Result&gt;
&lt;/FeratelDsiRS&gt;</string>

【问题讨论】:

标签: angularjs json angular parsing


【解决方案1】:

Cheerio

Cheerio 是我的首选,只是因为我一直将它用于项目,而且它已经存在。它也支持XML解析,

const $ = cheerio.load('<ul id="fruits">...</ul>', {
    normalizeWhitespace: true,
    xmlMode: true
});

与 CSS 选择器相同的基本 jQuery 式界面。

【讨论】:

    【解决方案2】:

    基本上你需要将XML转换为Json,我更喜欢使用自定义函数来解析XML

    function xmlToJson(xml) {
        var obj = {};
        if (xml.nodeType == 1) {
            // do attributes
            if (xml.attributes.length > 0) {
            obj["@attributes"] = {};
                for (var j = 0; j < xml.attributes.length; j++) {
                    var attribute = xml.attributes.item(j);
                    obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
                }
            }
        } else if (xml.nodeType == 3) { // text
            obj = xml.nodeValue;
        }
    
        if (xml.hasChildNodes()) {
            for(var i = 0; i < xml.childNodes.length; i++) {
                var item = xml.childNodes.item(i);
                var nodeName = item.nodeName;
                if (typeof(obj[nodeName]) == "undefined") {
                    obj[nodeName] = xmlToJson(item);
                } else {
                    if (typeof(obj[nodeName].push) == "undefined") {
                        var old = obj[nodeName];
                        obj[nodeName] = [];
                        obj[nodeName].push(old);
                    }
                    obj[nodeName].push(xmlToJson(item));
                }
            }
        }
        return obj;
    };
    

    【讨论】:

      猜你喜欢
      • 2015-03-02
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      相关资源
      最近更新 更多