【问题标题】:Xml String to object in c# using XDocument使用 XDocument 在 c# 中将 XML 字符串转换为对象
【发布时间】:2013-02-15 08:44:48
【问题描述】:

我似乎无法将我的 xml 字符串解析为自定义对象。这是我的代码:

    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>
...

【问题讨论】:

  • 您是否在调试器中单步调试过您的代码?如果没有,那就这样做。如果你有哪一行抛出异常?
  • 我已经使用调试器 (MonoDevelop)。异常出现在我的第一个代码部分的第 5 行 (List result = )

标签: c# linq parsing xml-parsing linq-to-xml


【解决方案1】:

你的根是 user 元素,所以改变:

from x in doc.Root.Elements("user")

from x in doc.Elements("user")

【讨论】:

  • 一个用户有两个元素:会话和用户。
  • 顶层只有一个用户,所以我假设它应该生成一个用户列表。所以那里没有空值?
【解决方案2】:
List<Account> result = (from o in doc.Elements()
             select new Account{ 
               User = o.Element("user").Value, 
               Session = o.Element("session").Value 
             }).ToList();

【讨论】:

    猜你喜欢
    • 2018-11-27
    • 1970-01-01
    • 2015-01-22
    • 2012-07-11
    • 2011-03-12
    • 2011-06-23
    • 1970-01-01
    • 2013-06-20
    相关资源
    最近更新 更多