How to read stackoverflow rss feed using linq to xml

烈酒焚心 提交于 2019-12-12 02:48:32

问题


I am trying read rss feed of stack overflow using Linq to xml. I am unable to get the entry nodes, as it is returning empty list. This I've tried so far, can any one point out what i am doing wrong here?

Here I am binding to the grid view:

private void StackoverflowFeedList()
{
    grdFeedView.DataSource = StackoverflowUtils.GetStackOverflowFeeds();
    grdFeedView.DataBind();
}

This is the method which will get all feeds:

public static IEnumerable<StackOverflowFeedItems> GetStackOverflowFeeds ()
{
    XNamespace Snmp = "http://www.w3.org/2005/Atom";
    XDocument RssFeed = XDocument.Load(@"http://stackoverflow.com/feeds");
    var posts = from item in RssFeed.Descendants("entry")
                select new StackOverflowFeedItems
                {
                   QuestionID = item.Element(Snmp +"id").Value,
                   QuestionTitle = item.Element(Snmp +"title").Value,
                   AuthorName = item.Element(Snmp +"name").Value,
                   CategoryTag = (from category in item.Elements(Snmp +"category")
                                  orderby category
                                  select category.Value).ToList(),
                   CreatedDate = DateTime.Parse(item.Element(Snmp +"published").Value),
                   QuestionSummary = item.Element(Snmp +"summary").Value
                };
    return posts.ToList();
}

And this is the class I am using for binding:

public class StackOverflowFeedItems
{
    public string   QuestionID { get; set; }
    public string   QuestionTitle { get; set; }
    public IEnumerable<string> CategoryTag { get; set; }
    public string AuthorName { get; set;  }
    public DateTime CreatedDate { get; set; }
    public string QuestionSummary { get; set; }
}

回答1:


You're not using the namespace variable you've declared. Try using

RssFeed.Descendants(Snmp + "entry")

(And likewise for all other places where you're referring to particular names.)

I'm not saying that's necessarily all of what you need to fix, but it's the most obvious problem. You should also consider using the explicit conversions of XElement and XAttribute instead of the Value property, e.g.

CreatedDate = (DateTime) item.Element(Snmp +"published")

I'd also encourage you to pay more attention to indentation, and use pascalCase consistently when naming local variables. (Quite why the namespace variable is called Snmp is another oddity... cut and paste?)



来源:https://stackoverflow.com/questions/9031652/how-to-read-stackoverflow-rss-feed-using-linq-to-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!