Reputation: 1389
I know that there are already solutions to this, but I'm really struggling with this problem.
I need to load an XML document from a URL and parse it to extract various pieces of information. I've tried using:
var doc = new XDocument();
doc = XDocument.Load(url);
This works fine in a standalone C# application but it won't work in the phone app. I believe that I need to do this asynchronously using WebClient.DownloadStringAsync
and WebClient.DownloadStringCompleted
, but I don't know how to get the document back from this so that I can parse it.
Thanks for your help.
EDIT: If it's of any use, I'm trying to access the BigOven API and get the XML returned from that.
EDIT#2: Code after trying the asynchronous method.
public static string xml;
private static void DownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
xml = e.Result; // this is always null
}
}
public static string QueryApi(string searchTerm)
{
WebClient wc = new WebClient();
wc.DownloadStringCompleted += DownloadCompleted;
wc.DownloadStringAsync(new Uri("http://www.w3schools.com/xml/note.xml"));
var doc = XDocument.Parse(xml);
}
EDIT#3: Code after trying to wait for the download to complete.
public static string xml;
public static XDocument doc;
private static void DownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
xml = e.Result; // this is always null
doc = XDocument.Parse(xml);
}
}
public static string QueryApi(string searchTerm)
{
WebClient wc = new WebClient();
wc.DownloadStringCompleted += DownloadCompleted;
wc.DownloadStringAsync(new Uri("http://www.w3schools.com/xml/note.xml"));
}
Upvotes: 0
Views: 239
Reputation: 5151
That looks much more convoluted than it should be. Similar to this answer, how about using HttpClient
, available on Windows Phone since 7.5:
static XDocument GetXml(string url)
{
using (HttpClient client = new HttpClient())
{
var response = client.GetStreamAsync(url);
return XDocument.Load(response.Result);
}
}
Upvotes: 1