biff
biff

Reputation: 79

XML data parsing in angular 2

Im new to angularjs2 and typescript,in my project i have a string variable comtaining xml as string, i need to process the string and access the data in the string according to node in the XML.Im having tough time by googling.Please help me out.

<groupDirectory>
<directoryDetails>
 <userId>extn5001</userId>
 <firstName>Park</firstName>
 <lastName>1</lastName>
 <groupId>communications</groupId>
 <extension>5001</extension>
</directoryDetails>
<directoryDetails>
 <userId>Yealinkt27ptest</userId>
 <firstName>Yealink T</firstName>
 <lastName>27P</lastName>
 <groupId>communications</groupId>
 <extension>4676</extension>
</directoryDetails>
<groupDirectory>

this is the xml i need to process.i need to access data according to nodes eg:name from

Upvotes: 2

Views: 11436

Answers (2)

VadimB
VadimB

Reputation: 5711

If you use angular-cli to bootstrap your application - next xml parser comes already with project installation.

https://github.com/Leonidas-from-XIV/node-xml2js

So you do not need to add extra modules for this. As it is classic commonJS module - you need use require to import it:

let parseString = require('xml2js').parseString;

So your code can looks like:

let parseString = require('xml2js').parseString;
let xml = "<root>Hello xml2js!</root>"

parseString(xml, function (err, result) {
  console.dir(result);
});

You will receive next output:

enter image description here

In any cases - if you even do not use angular-cli or want to use your preferred module to parse xml - use require to load it.

Upvotes: 0

dpetrini
dpetrini

Reputation: 1239

By today, the suggested code in other answer (which suggests node-xml2js) didn´t work. Instead of:

let parseString = require('xml2js').parseString;

I used:

import { parseString } from 'xml2js';

The remaining part was ok. Angular-cli used.

Upvotes: 1

Related Questions