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

biff
  • 79
  • 1
  • 2
  • 13

2 Answers2

1

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.

dpetrini
  • 1,169
  • 1
  • 12
  • 25
0

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 preffered module to parse xml - use require to load it.

VadimB
  • 5,533
  • 2
  • 34
  • 48
  • use `var` instead of `let` then. You do not use typescript/es6 in your project? – VadimB Feb 23 '17 at 08:54
  • ya i got it...i have another doubt how can i access data from the nodes – biff Feb 23 '17 at 09:16
  • can u help me to access values from the nodes in xml – biff Feb 27 '17 at 04:27
  • I have XML like this Tove Jani Reminder Don't forget me this weekend! Got JSON like this {"note":{"to":["Tove"],"from":["Jani"],"heading":["Reminder"],"body":["Don't forget me this weekend!"]}} – MeVimalkumar Nov 21 '17 at 08:25