1_
Load and populate list of Person (without children), filter and sort
C# XDocument data = XDocument.Load("persons.xml"); // select persons List<Person> people = ( from p in data.Descendants("person") where (int)p.Attribute("id") < 3 orderby (string)p.Element("name") select new Person() { Id = (int)p.Attribute("id"), Name = (string)p.Element("name"), } ).ToList();
2_
Load and populate list of Person (with children)
C# // select persons with children (nested elements) List<Person> people1 = ( from p in data.Descendants("person") select new Person() { Id = (int)p.Attribute("id").Value, Name = (string)p.Element("name"), Children = ( from ch in p.Descendants("child") select new Child() { Name = (string)ch.Element("name"), Age = (int)ch.Element("age") } ).ToList() } ).ToList();
3_
Load and populate children for persons with name 'John'
C# // select nested elements only - children List<Child> children = (from ch in config.Descendants("child") where (string)ch.Parent.Parent.Element("name") == "John" select new Child { Name = (string)ch.Element("name"), Age = (int)ch.Element("age") } ).ToList();
4_
How to read simple list of items
Items can be read from a simple list
XML <items> <item>1</item> <item>2</item> <items>
C# List<string> result = (from i in data.Descendants("item") select i.Value) .ToList();