{

Nodejs, How to Convert xml to CSV| Javascript


nodejs to Convert xml to CSV in Nodejs example

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 .

First, Let’s create a nodejs application using npm init command

npm init
 npm init -Y

This command creates a nodejs application with all default values

Next, Install @wmfs/xml2csv dependency to an application using 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 object xml2csv
  • Create an xml2csv object with options object and callback function

Options object contains the following properties

  • xmlPath: input xml path location and xml file name

  • csvPath : output csv path location

  • rootXMLElement: root tag for each XML record to read, In our example user.xml file, We have a user tag that contains data

  • headerMap: 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: Callback called and contains error and result error- returns an error object if an error result - count of records processed

Call back example to convert XML to CSV

Callback function called with first parameter as error and second parameter result.

Example for convert 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 following data

id,username,role,active
12,"john","admin",false

Promise example to convert xml to csv in nodejs

Promise.then contains two functions, First function is executed with resolved promise and a second function is called with 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 simplified version

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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.