Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data from xml, by linq, c#

Hi,

I have a problem with getting data from youtube xml: address of youtube xml: http://gdata.youtube.com/feeds/api/videos?q=keyword&orderby=viewCount

I try this, but the program doesn't go into the linq inquiry.

key = @"http://gdata.youtube.com/feeds/api/videos?q="+keyword+@"&orderby=viewCount";
youtube = XDocument.Load(key);
urls = (from item in youtube.Elements("feed")
       select new VideInfo
       {
            soundName = item.Element("entry").Element("title").ToString(),
            url = item.Element("entry").Element("id").ToString(),
       }).ToList<VideInfo>();

Anyone has idea, how to solve this? Thanks!

like image 420
MNie Avatar asked Oct 21 '22 21:10

MNie


1 Answers

Searching for elements in Linq to XML requires that you fully qualify with the namespace. In this case:

var keyword = "food";
var key = @"http://gdata.youtube.com/feeds/api/videos?q="+keyword+@"&orderby=viewCount";
var youtube = XDocument.Load(key);
var urls = (from item in youtube.Elements("{http://www.w3.org/2005/Atom}feed")
            select new
            {
                soundName = item.Element("{http://www.w3.org/2005/Atom}entry").Element("{http://www.w3.org/2005/Atom}title").ToString(),
                url = item.Element("{http://www.w3.org/2005/Atom}entry").Element("{http://www.w3.org/2005/Atom}id").ToString(),
            });
foreach (var t in urls) {
    Console.WriteLine(t.soundName + " " + t.url);
}

Works for me. To avoid writing out the namespace, one option is to search by local name (e. g. youtube.Elements().Where(e => e.LocalName == "feed"). I'm not sure if there's a more elegant way to be "namespace agnostic".

like image 53
ChaseMedallion Avatar answered Nov 01 '22 10:11

ChaseMedallion