Adam Kru...">

C # Reading XML with LINQ

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

My LINQ code is:

 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(); } 

Problem:

I have a generic list of the Customer class. This class contains 3 properties and another general list of the Account class. I managed to load the client data (id, fname, lname), but I do not know how to load the data from the Accounts subdirectory: (

the code gives me an error

An unhandled exception of type "System.ArgumentNullException" occurred in System.Xml.Linq.dll - Additional Information: The value cannot be null.

I tried many variations of the code, and I just could not get it to work :( Can someone post me a working code, how to download the subtree of accounts? Thanks a lot!

+4
source share
2 answers

Your code works for me. But you typed an error in XML - "Acount" instead of "Account" ...

+4
source
 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: Since the tag name in your xml is Acount , I used the same name.

+1
source

Source: https://habr.com/ru/post/1445268/


All Articles