Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: Convert XML to JSON

I wanted to convert the XML I received from Web API response to JSON in Angular 2. The application is developed in Nativescript. Not able to find a solution for this.

like image 241
dreamdeveloper Avatar asked Mar 16 '17 15:03

dreamdeveloper


1 Answers

I found an amazing package to make this very simple.

xml2js

For me on I am doing it in an angular 2 application but on the node side.

npm install xml2js --save

It is literally as simple as passing the xml like this,

var parseString = require('xml2js').parseString;
var xml = "<root>Hello xml2js!</root>"
parseString(xml, function (err, result) {
    console.dir(result);
});

In my app I had an xml file and used it like this,

var fs = require('fs');
var parseString = require('xml2js').parseString;

function requestCreditReport(callback) {
    fs.readFile('./credit-api/response.xml', 'utf8', function (err,data) {
        if (err) return callback(err);
        parseString(data, callback);
    });
}

See this jsfiddle

I hope this helps.

like image 137
wuno Avatar answered Sep 20 '22 22:09

wuno