如何从xml获取数据,由linq,c#

MNi*_*Nie 5 c# xml linq youtube microsoft-metro

嗨,

我从youtube xml获取数据时出现问题:youtube xml的地址:http://gdata.youtube.com/feeds/api/videos? q = keyword&orderby = viewCount

我试试这个,但程序没有进入linq查询.

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>();
Run Code Online (Sandbox Code Playgroud)

任何人都有想法,如何解决这个问题?谢谢!

Cha*_*ion 3

在 Linq to XML 中搜索元素要求您完全限定命名空间。在这种情况下:

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);
}
Run Code Online (Sandbox Code Playgroud)

对我有用。为了避免写出名称空间,一种选择是按本地名称进行搜索(例如youtube.Elements().Where(e => e.LocalName == "feed")。我不确定是否有更优雅的方式来“与名称空间无关”)。