使用RSS提要XML并显示信息
本文关键字:显示 信息 XML RSS 提要 使用 | 更新日期: 2023-09-27 18:14:24
我必须在我的Windows Phone 7应用程序中使用提要XML (RSS)并在ListBox
中显示这些信息。
下面我试着阅读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信息,并将它们显示为列表框项目?
你必须做两件事:
- 从URL下载提要XML
- 解析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文件的代码基于这篇关于使用HttpWebRequest
的优秀博客文章。