I am trying to add a record to my XML file.
Here is the original file
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<data>
<bookings>
<record>
<user>1</user>
<flight>1</flight>
</record>
</bookings>
</data>
Here is what I want
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<data>
<bookings>
<record>
<user>1</user>
<flight>1</flight>
</record>
<record>
<user>2</user>
<flight>2</flight>
</record>
</bookings>
</data>
Here is what is actually happening
<data>
<bookings>
<record>
<user>1</user>
<flight>1</flight>
</record>
</bookings>
<bookings>
<record>
<user>2</user>
<flight>2</flight>
</record>
</bookings>
</data>
You can see the bookings tag is getting duplicated.
Here is my code
fs.readFile(filePath, 'utf8', (err, data) => {
console.log('hey', data);
// convert XML to JSON
parseXml(data, function(err2, json) {
if (err2) console.log(err2);
json.data.bookings.push({
"record": [
{
"user": [
userId
],
"flight": [
flightId
]
}
]
});
// create a new builder object and then convert
// our json back to xml.
var builder = new xml2js.Builder();
var xml = builder.buildObject(json);
fs.writeFile(filePath, xml, function(err, data) {
if (err) console.log(err);
return 'Your booking is complete';
});
});
});
Any idea what's going on here?