Convert XML to JSON with NodeJS
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, {compact: true, spaces: 4});
console.log(result);
If you are choosing between xml2json and xml-js then as far as I understand the differences are:
- xml-js has much less dependencies and uses sax-js for xml parsing.
- xml2json has more dependencies including node-expat that requires python and can be a headache during npm i. But node-expat claims to be ~3 times faster than sax-js.
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.
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 = `<?xml version="1.0" encoding="UTF-8"?>
<TestScenario>
<TestSuite name="TS_EdgeHome">
<TestCaseName name="tc_Login">dt_EdgeCaseHome,dt_EdgeCaseRoute</TestCaseName>
<TestCaseName name="tc_Logout">dt_EdgeCaseRoute</TestCaseName>
</TestSuite>
<TestSuite name="TS_EdgePanel">
<TestCaseName name="tc_AddContract">dt_EdgeCaseHome,dt_EdgeCaseSpectrum</TestCaseName>
</TestSuite>
<TestSuite name="TS_EdgeRoute">
<TestCaseName name="tc_VerifyContract">dt_EdgeCaseRoute</TestCaseName>
<TestCaseName name="tc_Payment">dt_EdgeCaseRoute</TestCaseName>
</TestSuite>
<TestSuite name="TS_EdgeSpectrum">
<TestCaseName name="tc_ClientFeedback">dt_EdgeCaseSpectrum</TestCaseName>
</TestSuite>
</TestScenario>`;
console.log('JSON output', xmlParser.toJson(xmlString));
Hope this might be helps to you.