VOOZH about

URL: https://www.geeksforgeeks.org/javascript/convert-xml-to-json-using-javascript/

⇱ Convert XML to JSON using JavaScript - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Convert XML to JSON using JavaScript

Last Updated : 5 Aug, 2025

Convert XML to JSON effortlessly using JavaScript, enabling seamless integration and manipulation of XML data within your applications. JavaScript libraries like xml-js and xmldom Library simplify the conversion process, ensuring compatibility and efficiency.

Below are the approaches to convert XML to JSON in JavaScript:

Using xml-js Library

In this approach, we are using the xml-js library to handle XML to JSON conversion in JavaScript. This library provides a convenient 'xml2json' function, which directly transforms XML data into a JSON object. It offers options for formatting, including compactness and spacing.

Run the below command to install xml-js Library:

npm install xml-js

Example: The below example uses xml-js Library to convert XML to JSON in JavaScript.

Output:

{
"book": {
"title": {
"_text": "The Great Gatsby"
},
"author": {
"_text": "F. Scott Fitzgerald"
},
"genre": {
"_text": "Fiction"
}
}
}

Using DOM Parser

In this approach, we are using the 'xmldom' library to handle XML parsing in JavaScript. This method involves parsing the XML data into a DOM structure and then traversing the nodes to extract element names and their corresponding text content. This method results in a JSON object representing the structure and content of the original XML data.

Run the below command to install xmldom Library:

npm install xmldom

Example: The below example uses DOM Parser to convert XML to JSON in JavaScript.

Output:

{
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald",
"genre": "Fiction"
}
Comment
Article Tags: