簡體   English   中英

使用 NodeJS 從 XML 附加 JSON 解析

[英]append JSON parsing from XML using NodeJS

我有三個不同的 sample.xml 文件,我必須將它們轉換為 json 輸出。 我試圖將他們所有的輸出附加到一個 json 文件中。 這是我的代碼

const fs = require('fs');
const xml2js = require('xml2js');

parser = new xml2js.Parser({
    explicitArray: true
})
fs.readFile('sample.xml', (err, data) => {
    parser.parseString(data, (err, result) => {
        let output = JSON.stringify(result.planes.plane);
        fs.writeFile('output.json', output, 'utf8', (err) => {
            if (err) {
                throw err;
            } else {
                console.log('file created..')
            }
        })
    });

});

現在我知道函數 fs.appendfile() 但我不知道該怎么做? 我還有兩個文件名為:sample2.xml 和 sample3.xml

這是我嘗試過的,但問題是覆蓋而不是附加。

const fs = require('fs');
const xml2js = require('xml2js');
const async = require('async');
parser = new xml2js.Parser({
    explicitArray: true
})
let files = ['sample.xml', 'sample2.xml'];
async.map(files, fs.readFile, (err, files) => {
    if (err) {
        throw err;
    } else {
        files.forEach((file) => {
            parser.parseString(file, (err, result) => {
                let output = JSON.stringify(result.planes.plane);
                fs.appendFile('output.json', output, 'utf8', (err) => {
                    if (err) {
                        throw err;
                    } else {
                        console.log('file created..')
                    }
                })
            });
        })
    }
})

您需要讀取每個 xml 文件,從中獲取 json-data,然后將其寫入最終文件:

async.map(
  files,
  (file, cb) => {
    fs.readFile(file, (err, data) => {
      if (err) {
        cb(err)
      } else {
        parser.parseString(data, (err, result) => {
          cb(err, result.planes.plane)
        })
      }
    })
  },
  function (err, results) {
    if (err) {
      throw err
    } else {
      let output = JSON.stringify(results)
      fs.writeFile('output.json', output, 'utf8', (err) => {
        if (err) {
          throw err
        } else {
          console.log('file created...')
        }
      })
    }
  }
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM