问题
I have to consume a feed XML (RSS) in my Windows Phone 7 application and display those information in a ListBox
.
Following way I tried to read the content in 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");
}
Can someone please guide me how to proceed to get the XML info and to display them as ListBox items?
回答1:
You have to do two things:
- Download the feed XML from the URL you have there
- Parse the XML and process the resulting XML document
The following code shows how to do it:
(GetFeed
does part 1, handleFeed
does part 2, button1_Click
is the click handler which starts the feed download when the user clicks a button.)
// 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);
}
Most error checking is omitted for brevity. Some information about what XML elements to expect has Wikipedia. The code for downloading the XML file is based on this excellent blog post about using HttpWebRequest
.
来源:https://stackoverflow.com/questions/8123320/consume-rss-feed-xml-and-display-information