Recent Blogs



Blog Categories



C# - LINQ to XML

26 Dec 2009 by Cornel Human

In my previous article I showed some basic LINQ to objects. In this article I will look at LINQ to XML and how to parse,create and query XML with LINQ

To be able to use LINQ with XML you need to add the following to your class file :

using System.Xml.Linq;

Parsing XML

To use LINQ with XML we need to use the XElement class or the XDocument class. We will be using the XElement class which is the recommended class for most usage cases. The XDocument class can also be used but only if you have specific requirements to have certain document features in your XML like comments at the start of the XML.

To parse existing XML, simply use the XElement.Parse method:

 XElement parseSample = XElement.Parse("<root></root>");

Creating XML

Creating XML is easy and straight forward with LINQ. For our example we will create some basic XML that contains the Name,Surname and Age of a person. In order to do this we will create a method that returns an XElement class.

 private XElement CreatePerson(string Name, string Surname, int Age)

        {

            XElement person = new XElement("person");

 

            person.SetAttributeValue("Name", Name);

            person.SetAttributeValue("Surname", Surname);

            person.SetAttributeValue("Age", Age.ToString());

 

            return person;

        }

The constructor of the XElement class takes the name of the element as parameter. Adding XML attributes is as simple as calling the SetAttributeValue method.

To complete the general structure of our XML, and populate it with some test data for the Query section of these samples we use the following:

 XElement root = new XElement("xml");

 

            root.Add(CreatePerson("Bill", "Gates", 53));

            root.Add(CreatePerson("Steve", "Jobs", 54));

            root.Add(CreatePerson("Larry", "Ellison", 65));

            root.Add(CreatePerson("Larry", "Page", 36));

            root.Add(CreatePerson("Sergey", "Brin", 36));

Query XML using LINQ

The XML generated with the above code:

<xml>

  <person Name="Bill" Surname="Gates" Age="53" />

  <person Name="Steve" Surname="Jobs" Age="54" />

  <person Name="Larry" Surname="Ellison" Age="65" />

  <person Name="Larry" Surname="Page" Age="36" />

  <person Name="Sergey" Surname="Brin" Age="36" />

</xml>

Now we will use LINQ to return a list of Persons ordered by Age, then by surname. In the LINQ expression we use the Attribute method to return the value of a specific attribute. Also note that we use multiple fields for the order by clause.

 private void LINQtoXML_Sample_SortedByAge()

        {

            XElement root = XElement.Parse(ReturnXMLData());

 

            var listOfPersons = from person in root.Elements("person")

                                orderby System.Convert.ToInt32(person.Attribute("Age").Value),person.Attribute("Surname").Value

                                select person;

 

            foreach (XElement p in listOfPersons)

                Trace.WriteLine(String.Format("{0} , {1} , Age = {2}", p.Attribute("Name"), p.Attribute("Surname"), p.Attribute("Age")));

 

        }

Results

Name="Sergey" , Surname="Brin" , Age = Age="36"
Name="Larry" , Surname="Page" , Age = Age="36"
Name="Bill" , Surname="Gates" , Age = Age="53"
Name="Steve" , Surname="Jobs" , Age = Age="54"
Name="Larry" , Surname="Ellison" , Age = Age="65"

Conclusion

Using LINQ to XML is simple and powerful. LINQ to XML makes working with XML easy.