Convert XML to JSON with NodeJS

First of all, welcome to SO! Second of all, make sure you research your issues before you post questions on here - it'll increase your chances of getting answered and upvoted if the question is strong.

Commented Sep 11, 2018 at 17:55 Possible duplicate of Any recommendation for xml to json for Node.js? Commented May 31, 2019 at 17:56

You can give simple-xml-to-json a try, it's pretty compact, and has no external dependencies. npmjs.com/package/simple-xml-to-json

Commented Apr 25, 2020 at 19:16

9 Answers 9

I've used xml-js - npm to get the desired result.

First of all I've installed xml-js via npm install xml-js

Then used the below code to get the output in json format

var convert = require('xml-js'); var xml = require('fs').readFileSync('./testscenario.xml', 'utf8'); var result = convert.xml2json(xml, ); console.log(result); 
answered Sep 11, 2018 at 20:13 709 1 1 gold badge 7 7 silver badges 21 21 bronze badges

I tried the package in the accepted answer and I got this error: xml not formated well, but xml-js package worked perfectly. Thanks

Commented Jul 16, 2019 at 11:23

You can use xml2json npm for converting your xml in to json. xml2json.

Step 1:- Install package in you project

npm install xml2json

Step 2:- You can use that package and convert your xml to json

let xmlParser = require('xml2json'); let xmlString = `   dt_EdgeCaseHome,dt_EdgeCaseRoute dt_EdgeCaseRoute  dt_EdgeCaseHome,dt_EdgeCaseSpectrum  dt_EdgeCaseRoute dt_EdgeCaseRoute  dt_EdgeCaseSpectrum  `; console.log('JSON output', xmlParser.toJson(xmlString)); 

Hope this might be helps to you.

28.6k 8 8 gold badges 67 67 silver badges 82 82 bronze badges answered Sep 11, 2018 at 17:51 Dhiral Kaniya Dhiral Kaniya 2,021 2 2 gold badges 21 21 silver badges 33 33 bronze badges xml2json is not updated and work on old dependency and do not install on nodejs Commented Feb 17, 2023 at 3:17

It is deprecated and is not supported, It will not work on windows 11 for sure, It will fail on node-expat, they have posted solution on github/Readme.md Install Visual Studio C++ 2012 and run npm with the --msvs_version=2012 flag. but you cannot find or install visual studio c++ 2012 Microsoft doesn't support so cant use it anymore. npmjs.com/package/node-expat

Commented Jun 22, 2023 at 15:34

If you are choosing between xml2json and xml-js then as far as I understand the differences are:

Also be aware that xml2json and xml-js produce a bit different JSON. When I replaced xml2json with xml-js I had to add "._attributes" everywhere where values were in attributes.

answered Aug 30, 2019 at 10:09 4,519 2 2 gold badges 34 34 silver badges 35 35 bronze badges

In 6 simple ES6 lines:

xml2json = xml => < var el = xml.nodeType === 9 ? xml.documentElement : xml var h = h.content = Array.from(el.childNodes || []).filter(e => e.nodeType === 3).map(e => e.textContent).join('').trim() h.attributes = Array.from(el.attributes || []).filter(a => a).reduce((h, a) => < h[a.name] = a.value; return h >, <>) h.children = Array.from(el.childNodes || []).filter(e => e.nodeType === 1).map(c => h[c.nodeName] = xml2json(c)) return h > 
answered Nov 22, 2019 at 10:13 6,217 4 4 gold badges 30 30 silver badges 36 36 bronze badges

This loses mixed-content and element ordering (attribute ordering is at parser's choice anyways). Many disavow mixed-content anyways so.. Not a problem, just some users might care.

Commented Dec 13, 2019 at 15:39

Cruftless allows you to 'annotate' the data structure you want to match, to specify how it should be bound to a JSON representation of that same data.

So, if you define your template like this:

Then by calling .fromXML on the object created from it, passing in the XML you want to parse, you will get:

answered Feb 15, 2020 at 1:47 Wilfred Springer Wilfred Springer 10.9k 5 5 gold badges 57 57 silver badges 69 69 bronze badges

Trying to use it but the documentation is a bit thin on the notation and I could find no other examples of using fromXML in this way there.

Commented Jun 6, 2023 at 14:15

You can also try camaro

const < transform >= require('camaro') const xml = `   dt_EdgeCaseHome,dt_EdgeCaseRoute dt_EdgeCaseRoute  dt_EdgeCaseHome,dt_EdgeCaseSpectrum  dt_EdgeCaseRoute dt_EdgeCaseRoute  dt_EdgeCaseSpectrum   ` ;(async function () < const result = await transform(xml, < testSuites: [ '/TestScenario/TestSuite', < name: '@name', testCases: ['TestCaseName', < name: '@name', data: '.' >] > ] >) console.log(JSON.stringify(result, null, 2)) >)() 
answered Sep 3, 2019 at 2:41 Tuan Anh Tran Tuan Anh Tran 7,117 6 6 gold badges 38 38 silver badges 56 56 bronze badges
var fs = require('fs'); var xml2json = require('xml2js'); var parser = new xml2json.Parser(); var i = 0; fs.readFile('note.xml', function(err,data)< parser.parseString(data, function(err, result)< console.log(result); >); >);
answered Nov 29, 2021 at 7:10 rabia yılmaz rabia yılmaz 41 2 2 bronze badges

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Commented Nov 29, 2021 at 9:04

if you have a XML file, then you can read that XML file using fs in nodejs and then you can use "xml2json" npm package.

 const parser = require('xml2json'); const fs = require("fs") fs.readFile(uploadedFilePath, function(err,data)< if(err) < return res.send(); > else < jsonfile = JSON.parse(parser.toJson(data,)); > >); 
answered Jan 13, 2020 at 7:36 1,555 24 24 silver badges 33 33 bronze badges There is already an answer suggesting usage of the same tool with explanation. Commented Jan 17, 2022 at 9:51

To convert XML to JSON in Node.js, we'll use the xml2js library, a popular choice for parsing XML data. Install it by running:

npm install xml2js 

This library provides a simple API for converting XML to JSON and vice versa.

For demonstration purposes, let's create a sample XML file (input.xml) in your project directory:

   Node.js Guide John Doe 29.99  Web Development Basics Jane Smith 19.95   

Now, create a new file in your project directory and write the following code:

const fs = require('fs'); const xml2js = require('xml2js'); // Read the XML file const xml = fs.readFileSync('input.xml'); // Convert the XML to JSON xml2js.parseString(xml, < mergeAttrs: true >, (err, result) => < if (err) < throw err; >// The result is now a JavaScript object const json = JSON.stringify(result, null, 2); // Save the JSON to a file fs.writeFileSync('output.json', json); >);