Angular2: Convert XML to JSON

泄露秘密 提交于 2019-11-29 14:10:48

问题


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.


回答1:


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.




回答2:


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



回答3:


function parseXml(xmlStr) {
    var result;
    var parser = require('xml2js');
    parser.Parser().parseString(xmlStr, (e, r) => {result = r});
    return result;
}


来源:https://stackoverflow.com/questions/42838285/angular2-convert-xml-to-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!