How to extract information from xml using node.js


There are plenty of methods available to extract information from an XML file and I have used the XPath select method to fetch the tag values.


The following modules have to install using the NPM install Method.


var fs= require('fs'),
xml2js = require('xml2js');
const parser = new xml2js.Parser();
const xpath = require('xpath'),
dom = require('xmldom').DOMParser;

sample XML file name as test.xml.

<groceryShop>
<ownerName>xxxx</ownerName>
<name>DepartmentalStore</>
<address>bangalore</address>
<pincode>562320</pincode>
</groceryShop>

The above modules will drive the process to fetch the information.

//To read the file by using the readFile method which may be sync or async function

fs.readFile('test.xml',function(err , data){
if(err){
//display error
}
else{
// do whatever you want
}
});
//To Convert reading output(above output) into string values(parsing the XML)
var doc = new dom().parseFromString(data.toString(), 'text/xml');
// Add namespace URL

var select = xpath.useNamespaces({ url});
// To fetch information by using tag names
var tagOutput = select('//TagName/text()', doc)[0].nodeValue;


for example

  The groceryName variable is storing the value of the name from the XML file. Likewise, you have to read and fetch the information from the file.

    var groceryName = select('//name/text()', doc)[0].nodeValue;

  



Popular posts from this blog

How to clone a record using custom button in salesforce

Child to parent component communication in lwc