2011-11-14 35 views
3

我必須在Windows Phone 7應用程序中使用訂閱XML(RSS),並在ListBox中顯示這​​些信息。消費RSS訂閱XML和顯示信息

下列方式我試圖讀取XML中的飼料內容:

private void button1_Click(object sender, RoutedEventArgs e) 
    {    
      client.DownloadStringAsync(new Uri("http://earthquake.usgs.gov/eqcenter/recenteqsww/catalogs/eqs7day-M2.5.xml"), "usgs"); 
    } 

是否有人可以指導我如何繼續獲得XML信息,並將其顯示爲列表框的項目?

回答

5

你必須做兩件事情:

  1. 從網址下載飼料XML你必須有
  2. 解析XML和處理得到的XML文檔

下面的代碼演示瞭如何要做到這一點:

GetFeed做第1部分,handleFeed做第2部分,button1_Click是點擊處理程序的明星當用戶點擊按鈕時進行下載)

// this method downloads the feed without blocking the UI; 
// when finished it calls the given action 
public void GetFeed(Action<string> doSomethingWithFeed) 
{ 
    HttpWebRequest request = HttpWebRequest.CreateHttp("http://earthquake.usgs.gov/eqcenter/recenteqsww/catalogs/eqs7day-M2.5.xml"); 
    request.BeginGetResponse(
     asyncCallback => 
     { 
      string data = null; 

      using (WebResponse response = request.EndGetResponse(asyncCallback)) 
      { 
       using (StreamReader reader = new StreamReader(response.GetResponseStream())) 
       { 
        data = reader.ReadToEnd(); 
       } 
      } 
      Deployment.Current.Dispatcher.BeginInvoke(() => doSomethingWithFeed(data)); 
     } 
     , null); 
} 

// this method will be called by GetFeed once the feed has been downloaded 
private void handleFeed(string feedString) 
{ 
    // build XML DOM from feed string 
    XDocument doc = XDocument.Parse(feedString); 

    // show title of feed in TextBlock 
    textBlock1.Text = doc.Element("rss").Element("channel").Element("title").Value; 
    // add each feed item to a ListBox 
    foreach (var item in doc.Descendants("item")) 
    { 
     listBox1.Items.Add(item.Element("title").Value); 
    } 

    // continue here... 
} 

// user clicks a button -> start feed download 
private void button1_Click(object sender, RoutedEventArgs e) 
{ 
    GetFeed(handleFeed); 
} 

爲簡潔起見,大多數錯誤檢查被省略。關於什麼XML元素的預期信息有Wikipedia。用於下載XML文件的代碼基於使用HttpWebRequestthis excellent blog post

0
+2

注意,[唯一鏈接的答案(http://meta.stackoverflow.com/tags/link-only-answers/info)都望而卻步,SO答案應該是尋求解決方案的終點(而另一個引用的中途停留時間往往會隨着時間推移而過時)。請考慮在此添加獨立的摘要,並將鏈接保留爲參考。 – kleopatra

+0

這應該是一個評論,而不是一個答案。 –