Skip to content
Related Articles

Related Articles

Improve Article

Convert xml data into json using Node.js

  • Last Updated : 09 Apr, 2021

XML: Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. The design goals of XML focus on simplicity, generality, and usability across the Internet. It is a textual data format with strong support via Unicode for different human languages. Although the design of XML focuses on documents, the language is widely used for the representation of arbitrary data structures such as those used in web services.


        <name> sravan</name>
        <name> sudheer</name>

JSON: JSON stands for JavaScript Object Notation. It is a text-based data interchange format to maintain the structure of the data. JSON is the replacement of the XML data exchange format in JSON. It is easy to struct the data compare to XML. It supports data structures like arrays and objects and the JSON documents that are rapidly executed on the server. It is also a Language-Independent format that is derived from JavaScript. The official media type for the JSON is application/json and to save those file .json extension.


 { "Name":"sravan", "id":1 },
  { "Name":"sudheer", "id":2}


  • JSON and XML are “self describing” nature
  • JSON and XML are hierarchical
  • We can parse JSON and XML
  • We can include XAML along with JSON and vive versa.


  • JSON doesn’t use end tag whereas xml used end tag
  • JSON is shorter than xml
  • JSON is quicker to read and write
  • JSON can use arrays but xml can’t use arrays.


  • We need to import xml2js and fs module.
    1. xml2js used to convert XML to JSON
    2. fs stands for file system which is used to locate our local file system
  • String the results using JSON.stringify() method.


  • Install Modules:
    npm install fs xml2js


// import File System Module
import fs from "fs"
// import xml2js Module
import { parseString } from "xml2js"
//xml data
var xmldata = '<?xml version=”1.0" encoding=”UTF-8"?>' +
'<Student>' +
    '<PersonalInformation>' +
        '<FirstName>Sravan</FirstName>' +
        '<LastName>Kumar</LastName>' +
        '<Gender>Male</Gender>' +
    '</PersonalInformation>' +
    '<PersonalInformation>' +
        '<FirstName>Sudheer</FirstName>' +
        '<LastName>Bandlamudi</LastName>' +
        '<Gender>Male</Gender>' +
    '</PersonalInformation>' +
// parsing xml data
parseString(xmldata, function (err, results) {
// parsing to json
let data = JSON.stringify(results)
// display the json data
node code1.js


Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :