javascript - fast-xml-parser 解析数组不正确

标签 javascript arrays node.js

我遇到解析器错误地转换数组的问题。

数组创建代码(查看 DocFiles):

documents.push({
  // Document fields...
  DocFiles: []
});

for (const file of files) {
  documents[documents.length - 1].DocFiles.push({ File: file });
}

或者:

documents.push({
  // Document fields...
  DocFiles: files.map(file => ({ File: file }))
});

数组的形式如下:

documents: [
  {
    DocFiles: [
      { File: Object },
      { File: Object },
      { File: Object }
  },
  {
    DocFiles: [
      { File: Object },
      { File: Object },
      { File: Object }
  }
]

我想在 DocFiles Node 中的每个文档中获取什么:

<DocFiles>
    <File>{fileNodes}</File>
    <File>{fileNodes}</File>
    <File>{fileNodes}</File>
</DocFiles>

我得到了什么:

<DocFiles>
    <File>{fileNodes}</File>
</DocFiles>
<DocFiles>
    <File>{fileNodes}</File>
</DocFiles>
<DocFiles>
    <File>{fileNodes}</File>
</DocFiles>

我做错了什么?

  • 解析器选项:
const options = {
  attributeNamePrefix: '@_',
  attrNodeName: '@',
  textNodeName: '#text',
  ignoreAttributes: true,
  cdataTagName: '__cdata',
  cdataPositionChar: '\\c',
  format: true,
  indentBy: '    ',
  supressEmptyNode: true,
  tagValueProcessor: a => a,
  attrValueProcessor: a => a
}
  • 解析和编写代码:
for (const document of documents) {
  const parent = { Nomenclature: document };
  const fileName = `${Date.now().toString()}.xml`;
  const Parser = xml.j2xParser;
  const parser = new Parser(options);
  const value = await parser.parse(parent);

  await fs.writeFileSync(path.join(dir, fileName), value);
}
  • 解析之前:

  • 解析结果:

最佳答案

我找到了解决方案...

documents.push({
  // Document fields...
  DocFiles: {
    DocFile: files.map(file => file)
  }
});

感谢您的帮助:)

关于javascript - fast-xml-parser 解析数组不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55237063/

相关文章:

c# - 将普通窗口转换为模态窗口?

javascript - 用于游戏声音的 headless jplayer

java - 改变数组

mysql - 如何在 Docker 中设置 MySQL 并连接到它?

node.js - 将 Sails.js 项目部署到 Google 云 : "Fatal error: Unable to find local grunt."

javascript - 禁用桌面jquery

javascript - 如何在 Parse Cloud Code 中获取对象

python - 在 NumPy 中按列增长矩阵

c++ - 访问三个静态数组比访问一个包含 3x 数据的静态数组更快?

node.js - 使用Electron消费RESTful API