2012-07-06 88 views
4

我正在尝试阅读RSS提要并在我的C#应用​​程序中显示。我已经使用了下面的代码,它完美适用于其他RSS源。我想阅读这个RSS订阅--->http://ptwc.weather.gov/ptwc/feeds/ptwc_rss_indian.xml,下面的代码不适用于它。我没有收到任何错误,但没有任何反应,我想要显示RSS提要的文本框是空的。请帮忙。我究竟做错了什么?使用visual C来读取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; 

回答

8

看来,由于该项目是指定了两次有类别,然而在不同的命名空间的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(); 
} 
+1

谢谢你这么多。完美的作品:) – 2012-07-06 12:12:31