Angular2:将XML转换为JSON [英] Angular2: Convert XML to JSON

查看:97
本文介绍了Angular2:将XML转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我从Web API响应收到的XML转换为Angular 2中的JSON.该应用程序是用Nativescript开发的.找不到解决方案.

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.

推荐答案

我发现了一个非常了不起的软件包,可以使它变得非常简单.

I found an amazing package to make this very simple.

xml2js

对于我来说,我在angular 2应用程序中执行此操作,但在节点端.

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

npm install xml2js --save

从字面上讲,就像传递这样的xml一样简单,

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

在我的应用中,我有一个xml文件,并以此方式使用它,

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

请参阅此jsfiddle

我希望这会有所帮助.

这篇关于Angular2:将XML转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆