【问题标题】: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"?>
<FeratelDsiRS xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Status="0" Message="OK" xmlns="XXXXX">
<Result Index="1">
<Events>
.....
</Events>
</Result>
</FeratelDsiRS></string>
【问题讨论】:
标签:
angularjs
json
angular
parsing
【解决方案1】:
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;
};