Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

Linq to XML


For any application common approach is use database or XML documents to store backend data.

a. LINQ provides LINQ to SQL component to directly manipulate relational data, you can perform linq queries on Data directly.

b. For XML document .net framework provided LINQ to XML interface that enables In-memory XML document modification.

In this article I will describe LINQ to XML in detail with some sample examples.

What is LINQ to XML?

LINQ to XML is a LINQ-enabled, in-memory XML programming interface that enables you to work with XML from within the .NET Framework programming languages.

LINQ to XML is like the Document Object Model (DOM) in that it brings the XML document into memory. You can query and modify the document, and after you modify it you can save it to a file or serialize it and send it over the Internet. However, LINQ to XML different from DOM.

Using LINQ to XML, you can

a. Load XML from files or streams.
b. Serialize XML to files or streams.
c. Create XML from scratch by using functional construction.
d. Query XML using XPath-like axes.
e. Manipulate the in-memory XML tree by using methods such as Add, Remove, ReplaceWith, and SetValue.
f. Validate XML trees using XSD.
g. Use a combination of these features to transform XML trees from one shape into another.


Why LINQ to XML?

LINQ to XML enables you to create and modify XML documents easily by using LINQ query expressions instead of XPath or XQuery.

Compared with classic complex XML parsing approach LINQ to XML expressions are easy to read xml document and modify XML document.

Advantages using LINQ to XML:

1. LINQ to XML makes XML easier by providing a query experience that is similar to SQL.
2.   Allows to use query result as parameters to XElement and XAttribute object constructors enables a powerful approach to creating XML trees.
This approach, called functional construction, enables developers to easily transform XML trees from one shape to another.
3. Main advantage of LINQ to XML is its integration with LINQ, This integration allows you to write queries on the in-memory XML document to retrieve collections of elements and attributes.
   var result = xdoc.Descendants("Types")
                 .Where(n => n.Attribute("id").Value == "1");
4. Easy to create XML trees with LINQ to XML.
5. Compiled and in memory use, so it runs faster.
6. Allows for better string manipulation.
7. Ability to work directly with XML elements instead of creating a container XML document, as required with W3C DOM.
8. In-memory XML document modification that is powerful, yet simpler to use than XPath or XQuery.
9. You can perform sorting, grouping on xml data.

LINQ to XML Example with Sorting Data:

Following example LINQ to xml query sort’s student’s xml data by year in ascending order.


<?xml version="1.0" encoding="UTF-8"?>

LINQ to XML Query:

IEnumerable<decimal> Students =
         from el in doc.Elements("Students")
         let year = (decimal)el.Element("Year")
         orderby year
         select year;
           foreach (decimal student in Students)


LINQ to XML methods with use of extension method:

In following example count method is used with XML document  

var doc = XDocument.Load("~/nmk/students.xml");
int descendantsNodes =doc.Descendants().Count(); // counts ALL descendants elements
int childNodes = doc.Root.Elements().Count(); //counts direct children of the root element

User Defined Extension methods with LINQ to XML:

In following example I have created extension methods for data casting, those methods I used with LINQ to XML query.

  var products =
               from elem in xElem.Descendants("Product")
               orderby elem.Attribute("ProductName").Value
               select new Product
                   ProductId = elem.Attribute("ProductId").GetAsInteger(),
                   ProductName = elem.Attribute("ProductName").GetAsString(),
                   Category =
                   Price = elem.Attribute("Price").GetAsDecimal()

User Defined Extension method:

public static string GetAsString(this XAttribute attrbute)
    string ret = string.Empty;
    if (attrbute != null && !string.IsNullOrEmpty(attrbute.Value))
      ret = attrbute.Value;
    return ret;


Using existing .net Framework provided extension methods with LINQ to XML:

Following LINQ to XML query example returns valid products data for existing categories only

var ValidProductsDeatils = xElem
     x =>  x .Elements("Category")
         z => z.Attribute("Id").Value !="0"
         z =>

Invalid entry,please enter valid data.