How to get data from a webapi, parse it and display it on the Windows Phone 7
I made a post erlier this day about getting data from an webapi on the windows phone 7 but I think I overcomplicated things and were too unclear about what I wanted to do.
Now the thing I am trying to do is having a method going out and fetch some data in xml from a webapi and the returns it parsed to a class.
For example:
public List<Alliance> getAllianceList()
{
const string serviceUrl = "/eve/AllianceList.xml.aspx";
string xml = getXML(serviceUrl);
//Some parsing logic and then returns it.
}
In the getXML I am trying to get the data using the WebClient or the HttpWebRequest(Does not know wich one is the best) and then returns it. But the problem in my scenario is that it is async and I don't have much knowledge about async.
This is how I have made 开发者_开发技巧it so far:
private string _xml = "";
public string getXML(string serviceUrl)
{
var webClient = new WebClient();
webClient.DownloadStringCompleted += webClient_DownloadStringCompleted;
webClient.DownloadStringAsync(new Uri(ApiUrl + serviceUrl));
}
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
_xml = e.Result;
}
}
Now the thing I don't understand is how to go on with the parsing in getAllianceList if the request is async. Should I make the whole "chain" from and including getAllianceList async? And if so how?
Firstly I'd recommend HttpWebRequest to avoid blocking the UI Thread. Explained further in my post here.
WebClient, HttpWebRequest and the UI Thread on Windows Phone 7
You can then pass the stream you get in the callback to XDocument.Load() to parse the XML and do your business with it.
There's a basic sample of parsing this XML and databinding in my post below that begins with XDocument.Load() (in this case using a XAP file, but the principle is the same).
binding a Linq datasource to a listbox
Is this a valid way to do it?
private const string apiUrl = "http://api.eveonline.com";
public void UpdateAllianceList()
{
const string serviceUrl = "/eve/AllianceList.xml.aspx";
var wc = new WebClient();
wc.DownloadStringCompleted += (s, args) =>
{
var worker = new Thread(ParseXmlThread);;
worker.Start(args.Result);
};
wc.DownloadStringAsync(new Uri(apiUrl + serviceUrl));
}
private void ParseXmlThread(object xml)
{
// PARSING & ADDING TO THE VIEWMODEL.
}
精彩评论