xml2js: access xml node attribute

xml2js is XML to JavaScript object converter. It is very handy and available as nodejs package. If you haven't had a chance to try it out, you definitely should! The easiest way to install xml2js package is to use node package manager npm:

$ npm install xml2js

Let's make an example of how we can read attribute value of a node in XML. For this we need a sample xml, for the sake of simplicity we are going to declare it in the same file:

var xml =
"<apps>" +
"<app type='android'>" +
"<url>https://play.google.com/store/apps/details?id=com.olyv.wortschatz.ui</url>" +
"</app>" +
"<app type='web'>" +
"<url>http://wortschatz-olyv.rhcloud.com</url>" +
"</app>" +
"</apps>"

  As a first step we can will select second <app> node from xml. How to do it? The answer is below:

var xml2js = require('xml2js');
var extractedData = "";

var parser = new xml2js.Parser();
parser.parseString(xml, function(err, result){
  if(err) throw err;

  extractedData = result['apps']['app'][1]
});

console.log(extractedData);

Now if you run nodejs pointing to your js file, you will see something similar to

{ '$': { type: 'web' },
  url: [ 'http://wortschatz-olyv.rhcloud.com' ] }

At this point note that we used index '1' since indexes in javascript are starting from zero. Now we can go further and read value of an attribute as we were going to do. For this let's modify existing script and change path to our target attribute:

extractedData = result['apps']['app'][1].$.type;

Run the script again and now it will return  'web' word. The magic is done with the help of '$' which gives an access to the attribute object. And when crawled to the attribute object, we can access its values specifying value name.
    

Comments