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

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

问题描述

我有这种方法,可以从远程服务器接收XML响应,并且需要将XML转换为JSON,以便Angular 2可以处理数据:

I have this method where I receive an XML response from a remote server and I need to convert the XML to JSON so that Angular 2 can work with the data:

 private extractData(res: Response) {
    let xml = res["_body"]
    console.log(xml);
    var parser = require('xml2json');
    var json = parser.toJson(xml);
    return json
  }

我正在尝试使用此节点模块: https://www.npmjs.com/package/xml2json

I am trying to use this Node Module: https://www.npmjs.com/package/xml2json

现在该节点模块是用javascript(不是TypeScript)编写的,因此我不确定是否可以在Angular 2应用中使用它.

Now this node module is written in javascript (NOT TypeScript) so I'm not sure if I can even use it in an Angular 2 app.

我收到此编译错误:

./〜/isemail/lib/index.js中的错误 找不到模块:错误:不能 在'/Users/user/ebayTool/node_modules/isemail/lib'中解析'dns'@ ./~/isemail/lib/index.js 5:12-26 @ ./~/joi/lib/string.js @ ./~/joi/lib/index.js @ ./~/xml2json/lib/xml2json.js @ ./~/xml2json/lib/index.js @ ./~/xml2json/index.js @ ./src/app/hero.service.ts @ ./src/app/app.component.ts @ ./src/app/app.module.ts @ ./src/main.ts @多 webpack-dev-server/client? http://localhost:4200/ ./src/main.ts webpack:无法编译.

ERROR in ./~/isemail/lib/index.js Module not found: Error: Can't resolve 'dns' in '/Users/user/ebayTool/node_modules/isemail/lib' @ ./~/isemail/lib/index.js 5:12-26 @ ./~/joi/lib/string.js @ ./~/joi/lib/index.js @ ./~/xml2json/lib/xml2json.js @ ./~/xml2json/lib/index.js @ ./~/xml2json/index.js @ ./src/app/hero.service.ts @ ./src/app/app.component.ts @ ./src/app/app.module.ts @ ./src/main.ts @ multi webpack-dev-server/client?http://localhost:4200/ ./src/main.ts webpack: Failed to compile.

所以我的问题是如何在Angular 2中将XML转换为JSON,以及如何正确导入要在项目中使用的xml2json节点模块?

So my question is how to convert XML to JSON in Angular 2 and how I can properly import xml2json Node Module to be used in my project?

推荐答案

如果使用 angular-cli 引导您的应用程序-它已经带有用于转换xml的节点模块.

If you use angular-cli to bootstrap your application - it comes already with node module to convert xml.

https://github.com/Leonidas-from-XIV/node-xml2js

因此您不需要为此添加额外的模块.由于它是经典的commonJS模块-您需要使用require导入它:

So you do not need to add extra modules for this. As it is classic commonJS module - you need use require to import it:

let parseString = require('xml2js').parseString;

因此您的代码可以如下所示:

So your code can looks like:

let parseString = require('xml2js').parseString;
let xml = "<root>Hello xml2js!</root>"

parseString(xml, function (err, result) {
  console.dir(result);
});

您将收到下一个输出:

在任何情况下-如果您甚至不使用angular-clior都希望使用首选模块来解析xml-请使用require进行加载.

In any cases - if you even do not use angular-clior want to use your preffered module to parse xml - use require to load it.

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

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