0

How can I parse my XML response to JSON in angular.

That's my response:

<?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>
Word Rearranger
  • 1,306
  • 1
  • 16
  • 25
user3241084
  • 87
  • 1
  • 1
  • 11

2 Answers2

0

Cheerio

Cheerio is my goto, simply because I'm always using it for projects and it's already there. It supports XML parsing too,

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

Same basic jQuery-esque interface with CSS selectors.

Evan Carroll
  • 78,363
  • 46
  • 261
  • 468
0

Basically you need convert XML to Json, I prefer use customized function to parse 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;
};
junlan
  • 302
  • 1
  • 5