Angular2: Convert XML to JSON

前端 未结 3 1715
予麋鹿
予麋鹿 2020-12-16 04:13

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.

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-16 04:54

    This is if you are doing a POST and getting back XML response using Angular 2: Use xml2js - https://www.npmjs.com/package/xml2js

    1. npm install xml2js --save
    2. import in service file as:

      import * as xml2js from 'xml2js';
      
    3. Code:

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

提交回复
热议问题