Nodejs, How to Convert XML to CSV| Javascript
You can check more about xml and json types Nodejs Application
In Javascript, there is no direct solution to convert XML to JSON, We have npm library @wmfs/xml2csv
. You can also check other posts on npm command deprecate option is deprecated First, Let’s create a nodejs application using the npm init
command
npm init
npm init -Y
This command creates a nodejs application with all default values
Next, Install the @wmfs/xml2csv
dependency to an application using the below command
npm install xml2csv --save
This adds dependency
in package.json
as follows
"dependencies": {
"@wmfs/xml2csv": "^1.23.0",
}
Let’s declare XML file an for this example
<users>
<user id="u12">
<id>12</id>
<username>john</username>
<role>admin</role>
<active>false</active>
<create_date>2000-10-01</create_date>
</user>
</users>
How to Convert XML to CSV in Nodejs
- First import module
@wmfs/xml2csv
and loads module and creates an objectxml2csv
- Create an xml2csv object with
options
object and callback function
Options
object contains the following properties
xmlPath
: input XML path location and XML file namecsvPath
: output csv path locationrootXMLElement
: root tag for each XML record to read, In our example user.xml file, We have auser
tag that contains dataheaderMap
: mapping xml tag to csv columns HeaderMap declaration contains the field definition
[xmlTag, csvHeader, type, parent],
xmlTag: XML tag to be converted to CSV fields i.e id,username,role,active
csvHeader: xsv content fields
type: type of the field date, string, and number
parent: Optional parent tag of the XML tag
callback function: The callback called and contains an error and result error- returns an error object if an error result - count of records processed
Call back example to convert XML to CSV
The callback function is called with the first parameter as an error and the second parameter result.
Example for converting XML to CSV with asynchronous operation
const xml2csv = require("@wmfs/xml2csv");
xml2csv(
{
xmlPath: "user.xml",
csvPath: "csvfile.csv",
rootXMLElement: "user",
headerMap: [
["id", "id", "integer"],
["username", "username", "string"],
["role", "role", "string"],
["active", "active", "boolean"],
],
},
function (err, result) {
console.log(err);
console.log(result);
},
);
Output: csvfile.csv file is created with the following data
id,username,role,active
12,"john","admin",false
Promise example to convert xml to csv in nodejs
Promise.then
contains two functions, the First function is executed with a resolved
promise and the second function is called with a rejected
case Promise.catch
contains the error function called for promise error Here is Syntax
promise.then(
function(result) { // Calls success result },
function(error) { // calls an error case }
).catch(function(promiseerror){
// error case
});
The same above can be rewritten, replace lambda expressions and simplify the code clean.
promise
.then(
(result) => {
console.log("XML to CSV conversion completed", result);
},
(error) => {
console.log("XML to CSV conversion rejected", error);
},
)
.catch((error) => {
// error case
});
Here is an example with a simplified version You can check other posts on How to always run some code when a promise is resolved or rejected xml2csvPromise.js:
const xml2csv = require("@wmfs/xml2csv");
xml2csv(
{
xmlPath: 'user.xml',
csvPath: 'csvfile.csv',
rootXMLElement: 'user',
headerMap: [
['id', 'id', 'integer'],
['username', 'username', 'string'],
['role', 'role', 'string'],
['active', 'active', 'boolean'],
]
},).then((result)=>{
console.log("XML to CSV conversion completed",result);
},(err=>{
console.log("error conversion rejected",err);
}))
.catch((err)=>{
console.log("Conversion Failed",err);
}));
Conclusion
Learned multiple ways to convert xml to CSV with examples.