【问题标题】:How to split a file having multiple xml using Node js如何使用Node js拆分具有多个xml的文件
【发布时间】:2019-11-29 05:23:45
【问题描述】:

我正在学习 node-js,并试图解决下面提到的问题。我尝试使用 node.js 中可用的xml-splitterxml-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>

【问题讨论】:

  • 初始文件不是有效的 XML 文件,但包含两个连接的 XML 文件。这就是 XML NPM 模块不起作用的原因。

标签: node.js xml express split stream


【解决方案1】:

以下是解决您问题的完整工作代码。主要思想是使用 '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");
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多