Conversion of XML to JSON Format Using Node.Js in Two Different Scenario
Hi Geeks,
The steps you should follow are:
- Install Node.Js
- Create a Folder
- Create a javascript file inside a folder
- Go to that Folder directory in the NodeJs command prompt
- Install ‘xml-js’ package using
npm install --save xml-js
- You Can also Install Globally Using
npm install --global xml-js
- Install ‘fs’ package using
npm install fs
- Open the JavaScript in a Code Editor (Preferably Visual Studio Code or any other code editor of personal choice)
- Create an XML file inside the folder. which you want to see in the JSON format.
- You can skip step 9 if your scenario is to store XML in a variable which is shown in scenario 2.
- Write a Code in javascript file (eg:xmlfiletojson.js)
Scenario 1: When we have an XML file and we want to see it in JSON format.
12. Go to the folder directory in terminal and type Node followed by the javascript file name i.e D:\Node>node xmlfiletojson.js
Output:
Scenario 2: When we have an XML script that is not stored in a file instead it is stored in the variable and we want that in a JSON format
Output:
We can also use the above code as reference to convert data from one format to another:
- xmlFormat= convert.js2xml(js, options); // to convert javascript object to xml text
2. xmlFormat= convert.json2xml(json, options); // to convert json text to xml text
3. jsFormat= convert.xml2js(xml, options); // to convert xml text to javascript object
4. jsonFormat= convert.xml2json(xml, options); // to convert xml text to json text
Note:
While passing the data inside the method of convert object be careful about the method and the format you are passing.