-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
#12: create csv to xml node script for taxonomies
- Loading branch information
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}); |