2

Am a beginner in angular 4, I don't have enough knowledge how to handle XML to JSON and how to call Service in angular 4, please suggest

1 Answer 1

2

Based on the library http://goessner.net/download/prj/jsonxml/, I implemented a sample to receive XML data and parse them into an Angular4 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 plunkr: https://plnkr.co/edit/dj63ASQAgrNcLLlwyAum?p=preview.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. This conversion I got it, still am confusing how to convert in our my ts(typescript) file (example.ts) file.
No not confusing ,Just show the plunkr example and see you how conver in our ts file
Very Good! @FerasAlSous

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.