你好,在Windows Phone 8应用程序中我遇到了一个问题,从webclient下载反序列化xml ..我等待DownloadStringCompletedEvent,然后我使用下面的代码。
private void PopularDownloaded(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Result == null || e.Error != null)
{
MessageBox.Show("There was an error connecting to the server");
}
else
{
//MessageBox.Show(e.Result.ToString());
XDocument loadedpopData = XDocument.Load(e.Result);
var popdata = from query in loadedpopData.Descendants("pattern")
select new poppatterns
{
Title = (string)query.Element("title"),
UserName = (string)query.Element("userName"),
DateCreated = (string)query.Element("dateCreated"),
ImageUrl = (string)query.Element("imageUrl"),
ApiUrl = (string)query.Element("apiUrl"),
};
poplonglist.ItemsSource = popdata.ToList();
}
}
但它会引发以下异常:
System.Windows.ni.dll中发生未处理的“System.Reflection.TargetInvocationException”类型异常
如果我是项目中的本地xml文件,然后像这样加载
XDocument loadedpopData = XDocument.Load("Resources/top.xml");
它加载得很好所以它必须是
的东西XDocument loadedpopData = XDocument.Load(e.Result);
我试着查看e.Result,这是正确的数据。
任何想法我做错了什么?
答案 0 :(得分:2)
在e.Result
中,您有一个XML字符串,但XDocument.Load(string)
用于从文件加载数据,而字符串参数是文件的路径,您应该使用XDocument.Parse(e.Result)
加载XDocument
来自XML字符串数据。
在MSDN上发布关于Load
:XDocument.Load()
在MSDN上发布关于Parse
:XDocument.Parse()
答案 1 :(得分:1)
更改此行
//MessageBox.Show(e.Result.ToString());
XDocument loadedpopData = XDocument.Load(e.Result);
到
//MessageBox.Show(e.Result.ToString());
XDocument loadedpopData = XDocument.Parse(e.Result);
答案 2 :(得分:0)
快速烹饪样品。从LinqPad
获得结果代码:
var xml = new XElement("root");
for (var i = 0; i <10; i++)
{
xml.Add(new XElement("pattern", new XElement("title", "title" + i.ToString()),
new XElement("title", "title" + i.ToString()),
new XElement("userName", "userName" + i.ToString()),
new XElement("dateCreated", "dateCreated" + i.ToString()),
new XElement("imageUrl", "ImageUrl" + i.ToString()),
new XElement("apiUrl", "ApiUrl" + i.ToString())));
}
var xmlString = xml.ToString();
var loadedpopData = XDocument.Parse(xmlString);
var popdata = from query in loadedpopData.Descendants("pattern")
select new {
Title = (string)query.Element("title"),
UserName = (string)query.Element("userName"),
DateCreated = (string)query.Element("dateCreated"),
ImageUrl = (string)query.Element("imageUrl"),
ApiUrl = (string)query.Element("apiUrl"),
};
popdata.Dump();
结果:
标题UserName DateCreated ImageUrl ApiUrl title0 userName0 dateCreated0 ImageUrl0 ApiUrl0 title1 userName1 dateCreated1 ImageUrl1 ApiUrl1 title2 userName2 dateCreated2 ImageUrl2 ApiUrl2 title3 userName3 dateCreated3 ImageUrl3 ApiUrl3 title4 userName4 dateCreated4 ImageUrl4 ApiUrl4 title5 userName5 dateCreated5 ImageUrl5 ApiUrl5 title6 userName6 dateCreated6 ImageUrl6 ApiUrl6 title7 userName7 dateCreated7 ImageUrl7 ApiUrl7 title8 userName8 dateCreated8 ImageUrl8 ApiUrl8 title9 userName9 dateCreated9 ImageUrl9 ApiUrl9