【问题标题】:StartTag: invalid element name error while JSON to XML ConversionStartTag:JSON 到 XML 转换时元素名称无效错误
【发布时间】:2021-06-08 14:08:27
【问题描述】:

我从 mongoDB 得到一个数组,格式如下:

const data = await db.collection('myCollection').find(filterQuery).project(projection).toArray();
data.map(record => { record._id = record._id.toString()  }); // Converting objectId to string
// Data is: 
[
    {
        "_id": "60bf71cb31657b3e2c5e8d3c",
        "id": 1,
        "productName": "Phillips L8FB86ES",
        "copy1": "De beste wasmachine voor jou.",
        "copy2": "Vandaag besteld.",
        "copy3": "Morgen wassen.",
    },
   ...
]

我想将此数组转换为 XML

const convert = require('xml-js');
transformed = convert.json2xml(data, { compact: true, ignoreComment: true, spaces: 4 });

在此过程中我没有收到任何错误,但我将此文件上传到 cloudstorage,但上传的文件已损坏。我收到这样的错误:

This page contains the following errors:
error on line 1 at column 2: StartTag: invalid element name
Below is a rendering of the page up to the first error.

我真的不知道它有什么问题。如有任何帮助,我将不胜感激。

注意:我也试过xml2jsfast-xml-parserjstoxml 包。但结果没有改变。

注2:

当我登录 transformed(转换后的 XML 对象)时

<0>
    <_id>60bf71cb31657b3e2c5e8d3c</_id>
    <id>1</id>
    <productName>Phillips L8FB86ES</productName>
    <copy1>De beste wasmachine voor jou.</copy1>
    <copy2>Vandaag besteld.</copy2>
    <copy3>Morgen wassen.</copy3>
</0>
</1>
   ...

编辑 3: 我了解到 XML 标签不能以数字开头。那么如何将数组转成XML呢?

【问题讨论】:

    标签: javascript node.js xml xml-to-json


    【解决方案1】:

    FXP (fast-xml-parser) 默认使用数组的索引作为标记名解析 JS 数组。覆盖此行为;

    const parser = new j2xParser({
        rootNodeName: "records"
    });
    const result = parser.parse(cars);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-03
      • 1970-01-01
      • 2019-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多