Parse youtube feeds with linq

2019-07-01 10:32发布

I want to parse atom feeds of youtube channel. Here is the link of that rss atom feeds.

http://gdata.youtube.com/feeds/api/users/cokestudio/uploads?orderby=updated

 List<YTFeeds> lstYT = new List<YTFeeds>();
 XDocument xDocumentYT = XDocument.Load(Server.MapPath("XMLFile.xml"));
 XNamespace xmlns = "http://www.w3.org/2005/Atom";
lstYT.AddRange((from entry in xDocumentYT.Descendants(xmlns + "entry").Elements(xmlns + "media:group")
                        select new YTFeeds
                        {
                            Title = entry.Element(xmlns + "media:title").Value,
                            Description = entry.Element(xmlns + "media:description").Value,
                            Video = entry.Elements(xmlns + "media:player").ElementAt(1).Attribute("url").Value,
                            Image = entry.Elements(xmlns + "media:thumbnail").ElementAt(1).Attribute("url").Value

                        }).ToList());

I am getting an error which says invalid character or hexcode ":". I want to get elements from tag: <media:group> Please suggest.

1条回答
做个烂人
2楼-- · 2019-07-01 11:00

When writing out the name of an element using a namespace, you have to leave out the prefix, it will be handled for you. And in this case, you need a separate namespace instance to be able to get the media elements. So accessing the title, description, etc. should be like this:

var doc = XDocument.Load(Server.MapPath(@"XMLFile.xml"));
XNamespace xmlns = "http://www.w3.org/2005/Atom";
XNamespace media = "http://search.yahoo.com/mrss/";
var query =
    from entry in doc.Root.Elements(xmlns + "entry")
    let grp = entry.Element(media + "group")
    select new YTFeeds
    {
        Title = (string)grp.Element(media + "title"),
        Description = (string)grp.Element(media + "description"),
        Video = (string)grp.Element(media + "player").Attribute("url"),
        Image = grp.Elements(media + "thumbnail")
            .Select(e => (string)e.Attribute("url"))
            .First(),
    };
var lstYT = query.ToList();
查看更多
登录 后发表回答