使用XmlDocument.LoadFromUriAsync(UrlString)读取XML? [英] Read XML using XmlDocument.LoadFromUriAsync(UrlString)?

查看:213
本文介绍了使用XmlDocument.LoadFromUriAsync(UrlString)读取XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读一些XML,并希望用下面的代码读它,因为这是一个地铁Windows 8的应用程序。我虽然使用一些帮助就如何分析出每一个节点/元素等。谢谢!



 私人无效Button_Click(对象发件人, RoutedEventArgs E)
{
乌里UrlString =新的URI(http://v1.sidebuy.com/api/get/73d296a50d3b824ca08a8b27168f3b85/?city=nashville&format=xml);
变种的XmlDocument = XmlDocument.LoadFromUriAsync(UrlString);

text1.Text = xmlDocument.ToString();
}


解决方案

这是很难说是否你'再由XML部分或异步的部分混淆。你不这样做的解析自己在所有 - 的XmlDocument 这是否(虽然我想如果可以的话建议使用LINQ to XML)。然而,你的变量名和的ToString 通话建议你还没有明白, LoadFromUriAsync 返回的 IAsyncOperation< XmlDocument的> ,而不是一个的XmlDocument



实际上,它代表了承诺,一个的XmlDocument 将可在未来的某一时刻。这就是C#5的异步方法开始发挥作用......如果你改变 Button_Click 成一个异步方法,你可以写:

 专用异步无效Button_Click(对象发件人,RoutedEventArgs E)
{
乌里URI =新的URI(...);
XmlDocument的XmlDocument的等待= XmlDocument.LoadFromUriAsync(UrlString);
text1.Text = xmlDocument.ToString();
}

现在你的方法实际上将收益的调用者(在UI事件循环),当它击中的await表达式,假设该文件并未成为即时可用...但随后当文档被取出,你的方法的其余部分将执行(回UI线程),并你有,你可以,如果你想获取同步使用它的文件。


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();
}

解决方案

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.

这篇关于使用XmlDocument.LoadFromUriAsync(UrlString)读取XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆