Converting XML to JSON using Node.js

Siddharth
2 min readJun 1, 2021

Hi, Muggles

Today we are going to learn how to parse XML files into JSON using Node.js and express.

we need to install module using npm install — save xml-js

here we are using a small block of code to convert XML to JSON.

var convert = require(“xml-js”);

var xml = require(“fs”).readFileSync(path);

var xmlData = convert.xml2json(xml, {

compact: true,

spaces: 4

});

console.log(“converted json data “)

code explanation -:

At first, we are requiring xml-js module

then we are reading XML files using the fs.readFileSync method.

now we are using xml2json() function which is provided by xml-js API.

finally storing data in XML data variable and printing it.

more info about XML-js :

This library provides 4 functions: js2xml(), json2xml(), xml2js(), and xml2json().

var convert = require(‘xml-js’);

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

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

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

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

This is the code for converting an XML string into a JSON object.

This works for most cases. You can modify this code according to your own needs or requirements.

--

--