node js cheerio xml

user1222447 picture user1222447 · Jul 29, 2014 · Viewed 8.5k times · Source

I have the below code and it is working fine to get:

<troveUrl>http://trove.nla.gov.au/work/23043869</troveUrl> 

But I would like to get the value after 'id' in the following from the same page and cannot get it!

<work id="23043869" url="/work/23043869">

here is the code that i currently have

var request = require ('request'),
    cheerio = require ('cheerio');
    request('http://api.trove.nla.gov.au/result?key=6k6oagt6ott4ohno&zone=book&q-year1-date=2000&l-advformat=Thesis&l-australian=y&q-term2=&q-term3=&q-term0=&q-field1=title%3A&q-type2=all&q-field0=&q-term1=&q-type3=all&q-field3=subject%3A&q-type0=all&q-field2=creator%3A&q-type1=all&l-availability=y%2Ff&q=+date%3A[2000+TO+2014]&q-year2-date=2014&n=1', function (error, response, html) {
      if (!error && response.statusCode == 200) {
        var $ = cheerio.load(html);
        $('troveurl').each(function(i, element){
          var id = $(this);
          console.log(id.text());
        });
      }
    });

Any assistance appreciated.

Answer

Ben Fortune picture Ben Fortune · Jul 29, 2014

You should pass xmlMode: true in the options object, then you can parse it as XML.

You can then grab the tag and data with $('tag').attr('attribute') and $('tag').text() to get the data between the tags as you've done.

var request = require('request'),
    cheerio = require('cheerio');
request('http://api.trove.nla.gov.au/result?key=6k6oagt6ott4ohno&zone=book&q-year1-date=2000&l-advformat=Thesis&l-australian=y&q-term2=&q-term3=&q-term0=&q-field1=title%3A&q-type2=all&q-field0=&q-term1=&q-type3=all&q-field3=subject%3A&q-type0=all&q-field2=creator%3A&q-type1=all&l-availability=y%2Ff&q=+date%3A[2000+TO+2014]&q-year2-date=2014&n=1', function(error, response, html) {
    if (!error && response.statusCode == 200) {
        var $ = cheerio.load(html, {
          xmlMode: true
        });
        console.log($('work').attr('id'))
    }
});