如何使用Node js分割具有多个xml的文件

问题描述 投票:0回答:1

我正在学习node-js,正在尝试解决以下提到的问题。我试图使用node.js中可用的xml-splitter以及xml-stream npm模块,但是错误发生为Error: Text data outside of root node.

我有如下文件

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Party tonight!</body>
</note>
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
  <to>Jone</to>
  <from>Dove</from>
  <heading>Reminder</heading>
  <body>One batch, Two batch</body>
</note>

我想将文件分成两个,如图所示

文件1:

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Party tonight!</body>
</note>

文件2:

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
  <to>Jone</to>
  <from>Dove</from>
  <heading>Reminder</heading>
  <body>One batch, Two batch</body>
</note>
node.js xml express split stream
1个回答
0
投票

下面是解决问题的完整工作代码。主要思想是使用“ byline” NPM模块逐行读取文件,并检测“新” XML子文件何时启动。

const byline = require("byline");
const fs = require("fs");
const filePath = "./file.xml";

var stream = byline(fs.createReadStream(filePath));
var fileContents = {};
var indexSubFile = 0;
var subFileName;

stream.on("data", function(line) {
    line = line.toString(); // Convert the buffer stream to a string line
    if (/^<\?xml/.test(line)) {
        // New XML sub-file
        indexSubFile++;
        subFileName = "file" + indexSubFile + ".xml";
        fileContents[subFileName] = [line];
    } else {
        fileContents[subFileName].push(line);
    }
});
stream.on("error", function(err) {
    console.error(err);
});
stream.on("end", function() {
    var key;

    for (key in fileContents) {
        fs.writeFileSync(key, fileContents[key].join("\n"));
    }
    console.log("Done");
});
© www.soinside.com 2019 - 2024. All rights reserved.