C# 使用XDocument将Xml字符串转换为c中的对象
我似乎无法将xml字符串解析为自定义对象。这是我的密码:C# 使用XDocument将Xml字符串转换为c中的对象,c#,linq,parsing,xml-parsing,linq-to-xml,C#,Linq,Parsing,Xml Parsing,Linq To Xml,我似乎无法将xml字符串解析为自定义对象。这是我的密码: private Account parseXmlToAccount (String xml) { XDocument doc = XDocument.Parse(xml); Console.Out.WriteLine("a" + xml); List<Account> result = ( from x i
private Account parseXmlToAccount (String xml)
{
XDocument doc = XDocument.Parse(xml);
Console.Out.WriteLine("a" + xml);
List<Account> result =
(
from x in doc.Root.Elements("user")
select new Account()
{
Session = (string) x.Element("session").Value,
User = (string) x.Element("user").Value
}).ToList();
Console.Out.WriteLine("b");
return result.First();
和我的xml字符串:
<user>
<session>7981239761293767891</session>
<user>873948797862364</user>
</user>
以及我的错误消息:
UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object
at testMonoAndroidApp.LoginManager.<parseXmlToAccount>m__4 (System.Xml.Linq.XElement) <0x00044>
at System.Linq.Enumerable/<CreateSelectIterator>c__Iterator27`2<System.Xml.Linq.XElement, testMonoAndroidApp.Account>.MoveNext () <0x0015b>
at System.Collections.Generic.List`1<testMonoAndroidApp.Account>.AddEnumerable (System.Collections.Generic.IEnumerable`1<testMonoAndroidApp.Account>) <0x000ab>
at System.Collections.Generic.List`1<testMonoAndroidApp.Account>..ctor (System.Collections.Generic.IEnumerable`1<testMonoAndroidApp.Account>) <0x00093>
at System.Linq.Enumerable.ToList<testMonoAndroidApp.Account> (System.Collections.Generic.IEnumerable`1<testMonoAndroidApp.Account>) <0x0003b>
at testMonoAndroidApp.LoginManager.parseXmlToAccount (string) <0x0012f>
...
您的根是用户元素,因此更改:
from x in doc.Root.Elements("user")
到
您的根是用户元素,因此更改:
from x in doc.Root.Elements("user")
到
您是否在调试器中逐步完成了代码?如果没有,那么就这样做。如果你有哪一行抛出异常?我已经用调试器MonoDevelop解决了这个问题。异常在我的第一个代码部件列表result=的第5行强制转换,您是否在调试器中逐步完成了代码?如果没有,那么就这样做。如果你有哪一行抛出异常?我已经用调试器MonoDevelop解决了这个问题。在我的第一个代码部分列表result=中的第5行抛出了异常=一个用户有两个元素:session和user。顶层只有一个用户,所以我假设它应该生成一个用户列表。所以没有空值?一个用户有两个元素:会话和用户。顶层只有一个用户,所以我假设它应该生成一个用户列表。所以这里没有空值?
from x in doc.Elements("user")
List<Account> result = (from o in doc.Elements()
select new Account{
User = o.Element("user").Value,
Session = o.Element("session").Value
}).ToList();