How to parse xml in Angular 2

后端 未结 3 837
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 12:13

I\'m using an API that uses XML instead of JSON. Any suggestions on how to convert the following XML to JSON or how to properly use the data in an ngFor directive?

A

3条回答
  •  情深已故
    2020-11-28 12:49

    Based on the library http://goessner.net/download/prj/jsonxml/, I implemented a sample to receive XML data and parse them into an Angular2 application:

    var headers = new Headers();
    (...)
    headers.append('Accept', 'application/xml');
    
    return this.http.get('https://angular2.apispark.net/v1/companies/', {
      headers: headers
    }).map(res => JSON.parse(xml2json(res.text(),'  ')));
    

    To be able to use the library, you need to parse first the XML string:

    var parseXml;
    
    if (typeof window.DOMParser != "undefined") {
      parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
      };
    } else if (typeof window.ActiveXObject != "undefined" &&
       new window.ActiveXObject("Microsoft.XMLDOM")) {
        parseXml = function(xmlStr) {
          var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
          xmlDoc.async = "false";
          xmlDoc.loadXML(xmlStr);
          return xmlDoc;
      };
    } else {
      throw new Error("No XML parser found");
    }
    

    See this question:

    • Parse XML using JavaScript

    See this plunkr: https://plnkr.co/edit/dj63ASQAgrNcLLlwyAum?p=preview.

提交回复
热议问题