【问题标题】:C# Reading XML with LINQC# 使用 LINQ 读取 XML
【发布时间】:2012-11-10 22:52:14
【问题描述】:

我的 XML:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Bank>
  <Customer id="0">
    <FName>Adam</FName>
    <LName>Kruz</LName>
    <Accounts>
      <Acount id="0" money="1500" />
      <Acount id="1" money="6500" />
    </Accounts>
  </Customer>
</Bank>

我的 LINQ 代码:

private void loadCustomers()
{
    customers =
        (
            from c in XDocument.Load("database.xml").Root.Descendants("Customer")
            select
                new Customer((int) c.Attribute("id"), (string) c.Element("FName"), (string) c.Element("LName"))
                    {
                        accounts =
                            (
                                from a in c.Descendants("Account")
                                select new Account((int) a.Attribute("id"))
                                            {
                                                money = (double) a.Attribute("money")
                                            }
                            ).ToList()
                    }
        ).ToList();
}

问题:

我有一个客户类的通用列表。该类包含 3 个属性和另一个类 Account 的通用列表。我已经能够加载客户数据(id、fname、lname),但我不知道如何从 Accounts 子树加载任何数据:(

代码给了我一个错误

System.Xml.Linq.dll 中出现“System.ArgumentNullException”类型的未处理异常 - 附加信息:值不能为空。

我一直在尝试代码的许多变体,但我无法让它工作:(有人可以向我发布一个如何加载帐户子树的工作代码吗?非常感谢!

【问题讨论】:

  • 将您的 xml &lt;Acount 更改为 &lt;Account 或更改代码 c.Descendants("Acount")
  • 感谢我写这篇文章的时候很累:(

标签: c# xml linq


【解决方案1】:

您的代码对我有用。但是您在 XML 中输入错误 - “Acount”而不是“Account”...

【讨论】:

  • 是的,谢谢。我早上发现了这个:(似乎太多的编程和一点点睡眠不利于发现错误
【解决方案2】:
var xDoc = XDocument.Load("myfile.xml");
var list = xDoc.Descendants("Customer")
                .Select(c => new
                {
                    Id=c.Attribute("id").Value,
                    FName = c.Element("FName").Value,
                    LName = c.Element("LName").Value,
                    Accounts = c.Descendants("Acount")
                                .Select(a => new{
                                    Id= a.Attribute("id").Value,
                                    Money = a.Attribute("money").Value,
                                })
                                .ToList()

                })
                .ToList();

PS:由于你的xml中的标签名称是Acount,所以我使用了相同的名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    • 2012-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多