Skip to content

Commit

Permalink
#12: create csv to xml node script for taxonomies
Browse files Browse the repository at this point in the history
  • Loading branch information
tcatapano committed Apr 19, 2023
1 parent e8f53b8 commit 801f0d9
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions lib/csv2xml-taxonomy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const csv = require('csvtojson');
const builder = require('xmlbuilder');
const fs = require('fs');

const csvFilePath = 'input.csv';
const xmlFilePath = 'output.xml';

// Map CSV columns to XML elements and attributes with custom names
const elementMappings = {
'description': 'catDesc',
};
const attributeMappings = {
'label': 'xml:id',
'term': 'n'
};

// Convert CSV to JSON
csv()
.fromFile(csvFilePath)
.then((json) => {
// Create root element
const root = builder.create('taxonomy');

// Loop through JSON data and create XML elements and attributes with custom names
json.forEach((item) => {
const element = root.ele('category');
Object.keys(item).forEach((key) => {
if (elementMappings.hasOwnProperty(key)) {
element.ele(elementMappings[key], item[key]);
} else if (attributeMappings.hasOwnProperty(key)) {
element.att(attributeMappings[key], item[key]);
}
});
});

// Write XML to file
const xml = root.end({ pretty: true });
fs.writeFileSync(xmlFilePath, xml);
});

0 comments on commit 801f0d9

Please sign in to comment.