-1

I am using this javascript library xml2js to parse XML file to JSON format. This is the code:

const fs = require('fs');
const xml2js = require('xml2js');
const util = require('util');

const parser = new xml2js.Parser();

fs.readFile('data.xml', (err, data) => {
    parser.parseString(data, (err, result) => {
        var jsonFile = util.inspect(result, false, null, true);
        console.log(jsonFile);
        
    });
});

The parsing works. But there is one issue. $ symbol is added in as field. This is the XML data.

<?xml version="1.0" encoding="UTF-8"?><PFA><Entity id="123" action="add" date="31-Jul-2009"><ActiveStatus>Inactive</ActiveStatus></Entity></PFA>

and the json generated is below:

{
  PFA: {
    Entity: [
      {
        '$': { id: '123', action: 'add', date: '31-Jul-2009' },
        ActiveStatus: [ 'Inactive' ]
      }
    ]
  }
}

and when I tried to save it to mongodb, I got an error Error: key $ must not start with '$'

const fs = require('fs');
const xml2js = require('xml2js');
const util = require('util');

const parser = new xml2js.Parser();

fs.readFile('data.xml', (err, data) => {
    parser.parseString(data, (err, result) => {
        var jsonFile = util.inspect(result, false, null, true);
        var MongoClient = require('mongodb').MongoClient;
        var url = "mongodb://localhost:27017/";

        MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db("db");
        dbo.collection("entity").insertOne(result, function(err, res) {
            if (err) throw err;
            console.log("1 document inserted");
            db.close();
        });
        });        
    });
});
Steve
  • 2,963
  • 15
  • 61
  • 133

2 Answers2

1

Fields beginning with $ are not allowed in MongoDB because that syntax is reserved for operators. Similarly dots in field names are not allowed because they are used for document traversal (dot notation).

You need to change the data you are trying to persist.

D. SM
  • 13,584
  • 3
  • 12
  • 21
1

Solved it with this configuration

const parser = new xml2js.Parser({ mergeAttrs: true,   explicitArray: false});

For full documentation for xml2js is here

Steve
  • 2,963
  • 15
  • 61
  • 133