2

In the Angular2 project, I have one xml file that contains all information about an employee. i need to read employee data from that xml file and display in my component template.

How to read xml data using http service?

2
  • Your question is not clear. are you saying you have XML coming from an API? Commented Mar 3, 2017 at 11:19
  • pass the xml file to backend. parse it.. store the parsed data to db. Then provide the relevant data to the frontend via api, etc.. Commented Mar 3, 2017 at 11:21

3 Answers 3

1

For parsing you can try with xml2js: https://github.com/Leonidas-from-XIV/node-xml2js.

Check this other answer: XML data parsing in angular 2

In a short:

import { parseString } from 'xml2js';
/* ... */
let xml = "<root>Hello xml2js!</root>"
parseString(xml, function (err, result) {
   console.dir(result);
});
Sign up to request clarification or add additional context in comments.

Comments

0

The browser API already comes with an XML parser. Have a look at.

https://developer.mozilla.org/en-US/docs/Web/Guide/Parsing_and_serializing_XML

After you succeed parsing the document, you will navigate it with an API similar to the DOM navigation.

Some HTTP client libs may come with an option to parse XML (dont install a new one just to do that, check the one you are using!). I also had a quick look at angular's HttpClient and didnt find any XML parsing option on it at first.

The old XMLHttpRequest API also comes with an option to directly parse the response as XML (.responseXML), but you probably wont use it since you may be already using another thing for your HTTP client.

Comments

-1

You can do it with jQuery.parseXML, but you need to integrate jQuery with Angular.

jQuery.parseXML uses the native parsing function of the browser to create a valid XML Document. This document can then be passed to jQuery to create a typical jQuery object that can be traversed and manipulated.

For more details to integrate with jQuery see How to use jQuery with Angular2.

Using http service

let xml = "";
this.http.get(url)
  .map((res:Response) => res.text())
  .subscribe(data => {
        xml = data;
        console.log($.parseXML(xml));
     });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.