javascriptjqueryxml-parsingmusicbrainz

How to parse xml webservice response using Javascript or jQuery


I want to use following xml webservice. www.musicbrainz.org/ws/2/artist/?query=artist:michael jackson

which format is like below:

<metadata><artist-list offset="0" count="3418"><artist ext:score="100" type="Person" id="f27ec8db-af05-4f36-916e-3d57f91ecf5e"><name>Michael Jackson</name><sort-name>Jackson, Michael</sort-name><gender>male</gender><country>US</country>

I just want to parse this xml & get the gender from it . I used following code to parse xml . Here i get ext attribute of the artist but not working .

    $.ajax({
        type: 'GET',
        url: 'http://www.musicbrainz.org/ws/2/artist/?query=artist:michael jackson',
        dataType: 'xml',
        success: function(xml){
           // console.log(xml);
            $(xml).find('artist-list').each(function(){
            $(this).find('artist').each(function(){
                            var ext = $(this).attr('ext');
                            alert(ext);
                    });
            });
    }

});

Anybody can suggest me the example to parse xml using Javascript or jQuery.


Solution

  • $.ajax({ 
        type: 'GET', 
        url: 'http://www.musicbrainz.org/ws/2/artist/?query=artist:michael jackson',
        dataType: 'xml', 
        success: function(xml){ 
           $("artist", xml).each(function(){
               console.log($("gender", this).text());
           });
        }
    });
    

    Update:

    Just checked the webservice and I saw that not every artist has a gender tag specified. In this case you can use the following:

        $("artist", xml).each(function(){
             var gender = $("gender", this);
             if(gender.length>0)
                 console.log($(gender).text());
        });
    

    See JSFiddle Demo here.