我似乎無法解析我的xml字符串到自定義對象。這裏是我的代碼:Xml字符串在c#中使用XDocument對象
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();
而且Account.cs:
class Account
{
public string Session { get; set; }
public string User { get; set; }
public override string ToString()
{
return Session + " " + User;
}
}
和我的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>
...
你有沒有通過您的代碼在調試器階梯?如果沒有,那就這樣做。如果你有哪條線拋出異常? – 2013-02-15 08:45:53
我用調試器(MonoDevelop)降低了波谷。在我的第一個代碼部分的第5行中拋出異常(列表 result =) –
Sunkas
2013-02-15 08:47:57