我必须在Windows Phone 7应用程序中使用提要XML(RSS),并在ListBox
中显示这些信息。
下面我尝试阅读XML Feed中的内容:
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信息并将其显示为ListBox项目吗?
答案 0 :(得分:5)
你必须做两件事:
以下代码显示了如何执行此操作:
(GetFeed
执行第1部分,handleFeed
执行第2部分,button1_Click
是点击处理程序,用于在用户点击按钮时启动Feed下载。)
// 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文件的代码基于this excellent blog post关于使用HttpWebRequest
。
答案 1 :(得分:0)