Angular: Convert XML to JSON

前端 未结 3 1380
清酒与你
清酒与你 2020-12-10 07:26

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:

 priv         


        
相关标签:
3条回答
  • 2020-12-10 07:51

    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

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

    You will receive next output:

    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.

    0 讨论(0)
  • 2020-12-10 08:03
    function parseXml(xmlStr) {
        var result;
        var parser = require('xml2js');
        parser.Parser().parseString(xmlStr, (e, r) => {result = r});
        return result;
    }
    
    0 讨论(0)
  • 2020-12-10 08:03

    As xml2js uses sax as parser and is a native c module, I would recommend using txml. In your bundle it will only be 4kb and the api is very clean: txml.parse(xmlString)

    Disclaimer I am the author of txml.

    0 讨论(0)
提交回复
热议问题