Jon
Jon

Reputation: 8511

JavaScript - Read XML Document

I have a Youtube video ID and I want to get the video title for this ID. I've gotten the XML feed that contains the title, but am unsure how to extract it.

Sample of XML output

$.ajax({
    url: 'http://gdata.youtube.com/feeds/api/videos/' + videoId
}).done(function ( data ) {
    console.log( data.title ); //does not work
    console.log( data.entry.title ); //does not work
});

Upvotes: 0

Views: 417

Answers (2)

Daniel Uzunu
Daniel Uzunu

Reputation: 3246

What you get in the data argument is an XML document. JQuery will also help you to get the info you need in an easier way. The following code works:

$.ajax({
    url: 'http://gdata.youtube.com/feeds/api/videos/vnUwxDhE1kU'
}).done(function ( data ) {
    var $xml = $(data);
    console.log($xml.find('title').text());
});

See this link: http://tech.pro/tutorial/877/xml-parsing-with-jquery for more details.

Upvotes: 0

Kyle
Kyle

Reputation: 76

jQuery wont automatically convert XML to JSON for you. Simply use jQuery to treat the XML document as a DOM tree.

$(function () {
    $.ajax({
        url: 'http://gdata.youtube.com/feeds/api/videos/vnUwxDhE1kU',
        dataType: 'xml'
    }).done(function (data) {
        console.log('done', $(data).find('entry > title').text());
    });
});

Upvotes: 4

Related Questions