Read XML using XmlDocument.LoadFromUriAsync(UrlStr

2019-06-14 17:34发布

问题:

I am trying to read a bit of XML and want to read it using the code below as this is for a metro windows 8 application. I could use some help though on how to parse out each node/element etc. Thanks!

private void Button_Click(object sender, RoutedEventArgs e)
{
    Uri UrlString = new Uri("http://v1.sidebuy.com/api/get/73d296a50d3b824ca08a8b27168f3b85/?city=nashville&format=xml");
    var xmlDocument = XmlDocument.LoadFromUriAsync(UrlString);

    text1.Text = xmlDocument.ToString();
}

回答1:

It's hard to tell whether you're confused by the XML part or the async part. You don't do the parsing yourself at all - XmlDocument does that (although I'd recommend using LINQ to XML if you can). However, your variable name and ToString call suggest you haven't understood that LoadFromUriAsync returns an IAsyncOperation<XmlDocument>, not an XmlDocument.

Effectively, it represents the promise that an XmlDocument will be available at some point in the future. That's where C# 5's async methods come into play... if you change Button_Click into an async method, you can write:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    Uri uri = new Uri("...");
    XmlDocument xmlDocument = await XmlDocument.LoadFromUriAsync(UrlString);
    text1.Text = xmlDocument.ToString();
}

Now your method will actually return to the caller (the UI event loop) when it hits the await expression, assuming that the document hasn't become instantly available... but then when the document has been fetched, the rest of your method will execute (back on the UI thread) and you'll have the document which you can use as if you'd fetched it synchronously.