How to Convert CSV to XML in Node.js
While basic, tabular data is efficiently stored in CSV format, increasingly complex data relationships often require more intricate formats like XML. Thankfully, converting CSV to XML is easy with the ready-to-run Node.js code examples provided below. This code calls our CSV to XML conversion API, which conveniently allows you to customize your input request: you can determine up front if the first row of your CSV files should be used as column labels (if set to “false”, columns will be names Column0, Column1, etc.)
To call this API, your first step is to install the SDK; you can do so by either running the below command:
npm install cloudmersive-convert-api-client --save
Or, alternatively, including the below snippet in your package.json:
"dependencies": {
"cloudmersive-convert-api-client": "^2.6.3"
}
After that, you just need to copy the below code, and include a free-tier Cloudmersive API key in the Apikey.apiKey field. To get a free-tier API key, visit our website and register a free account:
var CloudmersiveConvertApiClient = require('cloudmersive-convert-api-client');
var defaultClient = CloudmersiveConvertApiClient.ApiClient.instance;
// Configure API key authorization: Apikey
var Apikey = defaultClient.authentications['Apikey'];
Apikey.apiKey = 'YOUR API KEY';
var apiInstance = new CloudmersiveConvertApiClient.ConvertDataApi();
var inputFile = Buffer.from(fs.readFileSync("C:\\temp\\inputfile").buffer); // File | Input file to perform the operation on.
var opts = {
'columnNamesFromFirstRow': true // Boolean | Optional; If true, the first row will be used as the labels for the columns; if false, columns will be named Column0, Column1, etc. Default is true. Set to false if you are not using column headings, or have an irregular column structure.
};
var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.convertDataCsvToXml(inputFile, opts, callback);
All done — nice and easy.