xml to json conversion
Use case
To convert the XML file to JSON file using node.js
Consider sample XML file name as test.xml which contains the following information
<groceryShop>
<ownerName>xxxx</ownerName>
<name>DepartmentalStore</>
<address>bangalore</address>
<pincode>562320</pincode>
</groceryShop>
There are different methods to convert XML to JSON .but here we will see customized JSON format where will see only required information details. we will create a JSON structure.
output:
var groceryitems = {
ownerName: xxxx,
name: DepartmentalStore,
address: bangalore,
pincode: 562301
};
// required modules:
const fs = require('fs'),
xml2js = require('xml2js');
//Step 1: To read file using fs.readfile syntax in node.js.it will fetch all the information
and store it into one variable
var data = fs.readFileSync('test.xml', 'utf-8');
//Step 2: Convert it into string
var doc = new dom().parseFromString(data.toString());
//Step 3: To extract information by using xpath ,select or known methods example,
var name = select('//FormName:name/text()', doc)[0].nodeValue;
var ownerName = select('//FormName:ownerName/text()', doc)[0].nodeValue;
var address = select('//FormName:address/text()', doc)[0].nodeValue;
var pincode = select('//FormName:pincode/text()', doc)[0].nodeValue;
//name will contain name of the groceryShop,
//ownerName will contain ownerName of the groceryShop,
//address will contain address of the groceryShop,
//pincode will contain pincode of the groceryShop,
//Step 4: To map with json variables
var groceryitems = {
GroceryownerName: ownerName,
Groceryname: name,
Groceryaddress: address,
Grocerypincode: pincode
};