Conversion of XML to JSON Format Using Node.Js in Two Different Scenario

Shreyas Prabhakar
2 min readJun 4, 2021

Hi Geeks,

The steps you should follow are:

  1. Install Node.Js
  2. Create a Folder
  3. Create a javascript file inside a folder
  4. Go to that Folder directory in the NodeJs command prompt
  5. Install ‘xml-js’ package using npm install --save xml-js
  6. You Can also Install Globally Using npm install --global xml-js
  7. Install ‘fs’ package using npm install fs
  8. Open the JavaScript in a Code Editor (Preferably Visual Studio Code or any other code editor of personal choice)
  9. Create an XML file inside the folder. which you want to see in the JSON format.
  10. You can skip step 9 if your scenario is to store XML in a variable which is shown in scenario 2.
  11. Write a Code in javascript file (eg:xmlfiletojson.js)

Scenario 1: When we have an XML file and we want to see it in JSON format.

12. Go to the folder directory in terminal and type Node followed by the javascript file name i.e D:\Node>node xmlfiletojson.js

Output:

fig1: You can see the XML script and the converted JSON Format in the terminal

Scenario 2: When we have an XML script that is not stored in a file instead it is stored in the variable and we want that in a JSON format

Output:

A sample output after we execute the above code
fig 2: Sample Output when we send the xml script directly via variable without the use of File Stream

We can also use the above code as reference to convert data from one format to another:

  1. xmlFormat= convert.js2xml(js, options); // to convert javascript object to xml text

2. xmlFormat= convert.json2xml(json, options); // to convert json text to xml text

3. jsFormat= convert.xml2js(xml, options); // to convert xml text to javascript object

4. jsonFormat= convert.xml2json(xml, options); // to convert xml text to json text

Note:

While passing the data inside the method of convert object be careful about the method and the format you are passing.

--

--

Shreyas Prabhakar

Full Stack Web Developer Basically Have Interest on React, Angular, Node, C#, ASP.NET Core, EF Core , ADO.NET and MSSQL