在C#中阅读Facebook Feed

时间:2011-11-02 13:37:06

标签: c# xml facebook

我想从Facebook页面读取XML流。当我尝试运行以下代码时,我收到错误“解析EntityName时出错。第10行,位置53”。为什么以及如何解决它?

class Program
{
    static void Main(string[] args)
    {
        var feed = RssManager.ReadFeed("https://www.facebook.com/feeds/page.php?id=145493382141206&format=rss20");
        foreach (var item in feed)
        {
            Console.WriteLine("***********************************************");
            Console.WriteLine("Title:" + item.title);
            Console.WriteLine("Link:" + item.link);
            Console.WriteLine("Description:" + item.description);
            Console.WriteLine("Language:" + item.language);
            Console.WriteLine("Publish Date:" + item.pubdate);
            Console.WriteLine("***********************************************");
        }
        Console.ReadLine();
    }
}

public class RssFeedItem
{
    public string title { get; set; }
    public string link { get; set; }
    public string description { get; set; }
    public string language { get; set; }
    public string pubdate { get; set; }
}

public static class RssManager
{
    public static List<RssFeedItem> ReadFeed(string url)
    {
        List<RssFeedItem> rssItems = new List<RssFeedItem>();
        HttpWebRequest rssFeed = (HttpWebRequest)WebRequest.Create(url);
        using (DataSet rssData = new DataSet())
        {
            var response = rssFeed.GetResponse();
            var data = response.GetResponseStream();
            rssData.ReadXml(data);
            foreach (DataRow datarow in rssData.Tables["item"].Rows)
            {
                rssItems.Add(new RssFeedItem
                {
                    description = Convert.ToString(datarow["description"]),
                    language = Convert.ToString(datarow["language"]),
                    link = Convert.ToString(datarow["link"]),
                    pubdate = Convert.ToString(datarow["pubdate"]),
                    title = Convert.ToString(datarow["title"])
                });
            }
        }
        return rssItems;
    }
}

2 个答案:

答案 0 :(得分:6)

下面的代码段会返回有关不支持的浏览器的错误页面。

HttpWebRequest rssFeed = (HttpWebRequest)WebRequest.Create("https://www.facebook.com/feeds/page.php?id=145493382141206&format=rss20");
Console.WriteLine(new StreamReader(rssFeed.GetResponse().GetResponseStream()).ReadToEnd());

如果添加以下行,它将正常工作:

rssFeed.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET4.0C; .NET4.0E)";

---编辑---

上述解决方案将使您能够传递rssData.ReadXml(data)处抛出的XML异常。但是你的代码仍然有解析RSS的问题(我注释掉了language = Convert.ToString(datarow["language"]))。

答案 1 :(得分:0)

您是否尝试过“pubDate”而不是“pubdate”?