6

我正在尝试读取 RSS 提要并在我的 C# 应用程序中显示。我使用了下面的代码,它适用于其他 RSS 提要。我想阅读这个 RSS 提要 ---> http://ptwc.weather.gov/ptwc/feeds/ptwc_rss_indian.xml,下面的代码对它不起作用。我没有收到任何错误但没有任何反应,我希望显示 RSS 提要的文本框是空的。请帮忙。我究竟做错了什么?

    public class RssNews
    {
        public string Title;
        public string PublicationDate;
        public string Description;
    }

    public class RssReader
    {
        public static List<RssNews> Read(string url)
        {
            var webResponse = WebRequest.Create(url).GetResponse();
            if (webResponse == null)
                return null;
            var ds = new DataSet();
            ds.ReadXml(webResponse.GetResponseStream());

            var news = (from row in ds.Tables["item"].AsEnumerable()
                        select new RssNews
                        {
                            Title = row.Field<string>("title"),
                            PublicationDate = row.Field<string>("pubDate"),
                            Description = row.Field<string>("description")
                        }).ToList();
            return news;
        }
    }


    private string covertRss(string url) 
    {
        var s = RssReader.Read(url);
        StringBuilder sb = new StringBuilder();
        foreach (RssNews rs in s)
        {
            sb.AppendLine(rs.Title);
            sb.AppendLine(rs.PublicationDate);
            sb.AppendLine(rs.Description);
        }

        return sb.ToString();
    }

//表单加载代码///

 string readableRss;
 readableRss = covertRss("http://ptwc.weather.gov/ptwc/feeds/ptwc_rss_indian.xml");
            textBox5.Text = readableRss;
4

1 回答 1

9

似乎 DataSet.ReadXml 方法失败,因为在项目中指定了两次类别,但是在不同的命名空间下。

这似乎效果更好:

public static List<RssNews> Read(string url)
{
    var webClient = new WebClient();

    string result = webClient.DownloadString(url);

    XDocument document = XDocument.Parse(result);

    return (from descendant in document.Descendants("item")
            select new RssNews()
                {
                    Description = descendant.Element("description").Value,
                    Title = descendant.Element("title").Value,
                    PublicationDate = descendant.Element("pubDate").Value
                }).ToList();
}
于 2012-07-06T12:07:50.697 回答