NodeJS: Convert XML to JSON

There are times, you would like to parse the xml data, say when you are dealing with Web Services returning xml data, you would like to parse the XML data to JSON and use within your application.

We are going to make use of an npm package named “xml-objtree”.

Prerequisites

This article assumes you have installed your machine with NodeJS. If not, please download and install the same.

Using Code

Before we code, let us first install the npm module ‘xml-objtree’ by running the below command
npm install --save xml-objtree

Here’s the demo code, where we are importing the xml-objtree module and further creating an object named ObjTree. We are making use of a sample CTA Bus tracker xml and paring the same to JSON by making a call to objTree.parseXML passing in the xml data.
  1. var ObjTree = require('xml-objtree');  
  2. var objTree = new ObjTree();  
  3. var xml = [  
  4.     '<?xml version="1.0" encoding="UTF-8"?>',  
  5.     '<bustime-response>',  
  6.     '<vehicle>',  
  7.     '<vid>509</vid>',  
  8.     '<tmstmp>20090611 10:28</tmstmp>',  
  9.     '<lat>41.92124938964844</lat>',  
  10.     '<lon>-87.64849853515625</lon>',  
  11.     '<hdg>358</hdg>',  
  12.     '<pid>3630</pid>',  
  13.     '<pdist>5678</pdist>',  
  14.     '<rt>8</rt>',  
  15.     '<des>Waveland/Broadway</des>',  
  16.     '</vehicle>',  
  17.     '<vehicle>',  
  18.     '<vid>392</vid>',  
  19.     '<tmstmp>20090611 10:28</tmstmp>',  
  20.     '<lat>41.91095733642578</lat>',  
  21.     '<lon>-87.64120713719782</lon>',  
  22.     '<hdg>88</hdg>',  
  23.     '<pid>1519</pid>',  
  24.     '<pdist>11203</pdist>',  
  25.     '<rt>72</rt>',  
  26.     '<des>Clark</des>',  
  27.     '</vehicle>',  
  28.     '</bustime-response>'  
  29. ].join('\n');  
  30. var json = objTree.parseXML(xml);  
  31. console.log(JSON.stringify(json));  
Running the Program

Navigate to the project folder and run the below command.
“node index.js”.

Program
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now