从URL加载xml文件到XDocument
问题描述:
道歉,如果这是一个简单的,但我很新的C#。在WP7应用程序中,我试图使用XDocument.Load()方法将XML文件(特别是Blogger提要)加载到XDocument中。但是,当我尝试以下方法:从URL加载xml文件到XDocument
XDocument data = XDocument.Load("http://destroyedordamaged.blogspot.com/feeds/posts/default");
我得到的错误:
无法打开 'http://destroyedordamaged.blogspot.com/feeds/posts/default'。 Uri参数必须是指向Silverlight应用程序的XAP包内的内容的相对路径。如果您需要加载从任意开放的内容,请使用参阅加载XML内容的文档的WebClient/HttpWebRequest的
所以我不得不环顾四周,发现有人谁认为我这样做,而不是:
WebClient wc = new WebClient();
wc.OpenReadCompleted += wc_OpenReadCompleted;
wc.OpenReadAsync(new Uri("http://destroyedordamaged.blogspot.com/feeds/posts/default"));
和:
private void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error != null)
{
Console.WriteLine("THERE IS AN ERROR: "+e.Error.Message);
return;
}
using (Stream s = e.Result)
{
data = XDocument.Load(s);
}
}
但是,这似乎并没有工作,要么;它不会将任何内容加载到XDocument中。有什么我在这里失踪?我想找出将XML从Feed中加载到XDocument中的最简单方法。
我环顾四周,但似乎每个人都有这样的问题,他们已经指向他们的代码在一个特定的.xml文件,而不是像没有我的扩展名的URL。
我会很感激你可以提供任何输入。提前致谢。
答
尝试使用DownloadStringAsync
代替OpenReadAsync
:
var webClient = new WebClient();
webClient.DownloadStringCompleted += RequestCompleted;
webClient.DownloadStringAsync(new Uri(SOURCE));
而且RequestCompleted
代码:
private void RequestCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
var feedXml = XDocument.Parse(e.Result);
// (...)
}
}
我在我的应用程序前一段时间使用过,所以我敢肯定它的工作原理。
非常感谢 – user1349655 2012-07-08 01:12:26