Angular2: convert XML to JSON

I wanted to convert the XML I got from the Web API response to JSON in Angular 2. The application was developed in Nativescript. Could not find a solution for this.

+4
source share
2 answers

I found an amazing package to make it very simple.

xml2js

For me, I do this in an angular 2 application, but on the node side.

npm install xml2js --save

It is literally as simple as passing xml like this,

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

In my application, I had an xml file and it used it,

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

Check out this jsfiddle

Hope this helps.

+5
source

, POST XML Angular 2: xml2js - https://www.npmjs.com/package/xml2js p >

  • npm install xml2js -g
  • : import * xml2js 'xml2js';

  • :

    let formdata = new URLSearchParams();
    formdata.set('username','username');
    formdata.set('pw','pw'); 
    let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded' });
    
    let options = new RequestOptions({ headers: headers, method: RequestMethod.Post});
    
    postData () {
    
         this.http.post(this._yourUrl, formdata.toString(), options)
         //convert to JSON here
         .map(res => {
                xml2js.parseString( res.text(), function (err, result) {
                console.dir(result); // Prints JSON object!
             });
         })
         .subscribe(data => { 
              console.log(data);              
         });
    }
    
+3

Source: https://habr.com/ru/post/1672479/


All Articles