我有一个xml文件,其中包含10个学生的数据。每个学生的详细信息都以学生标签为界。如何使用Node.js从xml文件中检索单个数据?
答案 0 :(得分:0)
您有两个选择。您可以使用fs中的内置库来读取文件。如果未指定编码,您将获得可以读取的原始缓冲区。
https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback
此外,为了进一步帮助您,可以使用xml2js库。 例子
const xml2js = require('xml2js');
const fs = require('fs');
const parser = new xml2js.Parser({ attrkey: "ATTR" });
// this example reads the file synchronously
// you can read it asynchronously also
let xml_string = fs.readFileSync("data.xml", "utf8");
parser.parseString(xml_string, function(error, result) {
if(error === null) {
console.log(result);
}
else {
console.log(error);
}
});
https://usefulangle.com/post/106/nodejs-read-xml
然后,您可以根据标签解析下载数据的方式。我会看看split函数
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
让我知道这是否有帮助