2012-11-10 112 views
4

我的XML:C#读取XML使用LINQ

<?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),但我不知道如何加载从帐户子树:(任何数据

代码给我一个错误

未处理的异常类型“System.ArgumentNullException”发生在System.Xml.Linq.dll - 其他信息:值不能为空

我一直在试图代码的许多变种,我只是不能使它工作:(。可有人张贴了我一个工作代码如何加载帐户子树?多谢!

+2

改变你的XML'<帐户'为'<帐户'或更改代码'c.Descendants(“Acount”)' –

+0

谢谢我是相当累了的时候,我写这个:( – Safiron

回答

4

您的代码为我工作。但你已经在XML中输入错误 - “帐户”,而不是“账户”...

+0

+1好对象,就应该可以正常 –

+0

好的,谢谢,我发现了这一点在上午:(似乎太多编程和睡眠的点点不适合寻找错误 – Safiron

1
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,我用同样的名字。

+0

完美的作品非常感谢你! – Safiron