Read XML using XmlDocument.LoadFromUriAsync(UrlString)?

限于喜欢 提交于 2019-12-08 13:59:49

问题


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.



来源:https://stackoverflow.com/questions/9650232/read-xml-using-xmldocument-loadfromuriasyncurlstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!