且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Angular:将XML转换为JSON

更新时间:2023-02-04 08:39:29

如果使用 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.