From 801f0d9029811f3dfeab56e15774b825d1b4b204 Mon Sep 17 00:00:00 2001 From: Terry Catapano Date: Tue, 18 Apr 2023 20:47:39 -0700 Subject: [PATCH] #12: create csv to xml node script for taxonomies --- lib/csv2xml-taxonomy.js | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 lib/csv2xml-taxonomy.js diff --git a/lib/csv2xml-taxonomy.js b/lib/csv2xml-taxonomy.js new file mode 100644 index 00000000..d279d5e2 --- /dev/null +++ b/lib/csv2xml-taxonomy.js @@ -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); + });