gpt4 book ai didi

c# - 使用 RSS 提要 XML 并显示信息

转载 作者:太空狗 更新时间:2023-10-30 00:56:18 25 4
gpt4 key购买 nike

我必须在我的 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 信息并将它们显示为列表框项目吗?

最佳答案

你必须做两件事:

  1. 从您的 URL 下载提要 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文件的代码基于this excellent blog post关于使用 HttpWebRequest

关于c# - 使用 RSS 提要 XML 并显示信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8123320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com