I am trying with “node js convert xml to json” .I have xml file which has a larger data around 50,000 nodes,so due to that its unable to covert with javascript.
So is there any module available with node so i can try “node js covert xml to json“.
It can try node js convert xml to json , here I am giving an example that will convert small xml file to json data file or it can be displayed json data.
Here is my small xml file :
<?xml version="1.0" encoding="UTF-8" ?>
<website>
<company>Php Dedicated Develpers</company>
<owner>Bhaskar Bhatt</owner>
<url>http://phpdedicateddevelopers.com</url>
<employee>
<firstname>John</firstname>
<lastname>Doe</lastname>
</employee>
<employee>
<firstname>John</firstname>
<lastname>Doe</lastname>
</employee>
</website>
Before we proceed further , we must know that the “XML2JS” module is installed,if it is not installed then
Please run below command to install xml2js module:
for windows:
npm install xml2js
for ubuntu:
sudo npm install xml2js
As if you have installed, it should be exist in node_modules >> xml2js module.
Now, we will create task.js which will have the below code to convert xml to json using node.js.
var fs = require("fs");
var fileName = "web.xml";
var parser = require("xml2js");
//read xml file
fs.readFile(fileName, function(err, data) {
//converting xml to json
parser.parseString(data, function (err, result) {
//To store the json to file
fs.writeFile("data.json",JSON.stringify(result),function(err,response){
});
//To display the json
console.log(JSON.stringify(result));
});
});
Now, final step to run below code to convert xml to json.
node task.js