0

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"));
}
George Brighton
  • 5,131
  • 9
  • 27
  • 36
helencrump
  • 1,351
  • 1
  • 18
  • 27

1 Answers1

1

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);
    }
}
Community
  • 1
  • 1
George Brighton
  • 5,131
  • 9
  • 27
  • 36
  • No luck I'm afraid - I suspect there's a problem elsewhere in my program. – helencrump Jul 30 '15 at 09:12
  • Did you get an exception? Try a minimal example and build it up from there. – George Brighton Jul 30 '15 at 09:17
  • Solved the problem by doing it asynchronously and making all necessary methods asynchronous, not just the ones that get the XML. Thanks for the help though, especially with getting HttpClient to work. :) – helencrump Jul 30 '15 at 09:32