Search code examples
javascriptmongodbxml2js

xml2js - Error: key $ must not start with '$'


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();
        });
        });        
    });
});

Solution

  • Solved it with this configuration

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

    For full documentation for xml2js is here