Read xml file data in angular2

2020-07-23 08:49发布

问题:

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?

回答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);
});


回答2:

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.



回答3:

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));
     });