2012-07-06 93 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