1. Loading simple elements
2. Loading elements with nested elements
3. Loading elements deep in hierarchy
4. Reading simple list
Linq to XML allows querying XML data without using xPath. Overview on hookedonlinq.com
Assuming input data like below
XML <?xml version="1.0" encoding="utf-8" ?> <persons> <person id="1"> <name>John</name> <children> <child> <name>Peter</name> <age>10</age> </child> </children> </person> <person id="2"> <name>Paul</name> <children> <child> <name>Max</name> <age>12</age> </child> </children> </person> </persons>that can be represented by classes
C# public class Person { public int Id; public string Name; public List<Child> Children; } public class Child { public string Name; public int Age; }
1. Loading simple elements
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. Loading elements with nested elements
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. Loading elements deep in hierarchy
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. Reading 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();