StartTag: invalid element name error while JSON to XML Conversion

811 Views Asked by At

I'm getting an array from mongoDB formatted like this:

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.",
    },
   ...
]

And I want to convert this array to XML

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

I do not get any error during the process, but I upload this file to cloudstorage and the file uploaded there becomes corrupted. And I'm getting an error like this:

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.

I really don't know what's wrong with it. I will be grateful for any help.

Note: I tried xml2js, fast-xml-parser and jstoxml packages too. But result didn't change.

Note2:

When I log transformed (Converted XML object)

<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>
   ...

Edit 3: I learned that XML tags cannot start with numbers. Then how do I convert an array to XML?

1

There are 1 best solutions below

0
On

FXP (fast-xml-parser) by default parse a JS array using array's index as tagname. To override this behaviour;

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