How to parse xml file to array in JavaScript node.js

前端 未结 1 1843
予麋鹿
予麋鹿 2021-01-23 06:10

I\'m beginner and I have problem with parse data from xml file to array in Node.js?

Data from xml:



        
相关标签:
1条回答
  • 2021-01-23 06:27

    Check out one of the many XML Parser Packages on npm.

    For example: xml2js

    var parseString = require('xml2js').parseString;
    var xml = "<root>Hello xml2js!</root>"
    parseString(xml, function (err, result) {
        console.dir(result);
    });
    

    If you need help reading the xml File in, check out the nodeJs File System Libary.

    Doc for reading a file:

    var fs = require('fs');
    
    fs.readFile('/etc/data.xml', (err, data) => {
      if (err) throw err;
      console.log(data);
    });
    

    EDIT: To make it all in one function:

    function loadXML(cb) {
      fs.readFile('test_data.xml', function(err, data){
        parseString(data, function (err, result) {
          cb(result.xml.record)
        });
      });
    }
    
    loadXML(function(yourRecods) {
      // do whatever
    });
    
    0 讨论(0)
提交回复
热议问题