我有三个不同的 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...')
}
})
}
}
)
关于javascript - 使用 NodeJS 从 XML 附加 JSON 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51863364/