LINQ to XML is a built-in LINQ data provider that is implemented within the “System.Xml.Linq” namespace in .NET 3.5.

LINQ to XML enables you to read, construct and write XML data.  You can use LINQ to XML to perform LINQ queries over XML that you retrieve from the file-system, from a remote HTTP URL or web-service, or from any in-memory XML content. 

In this post I will show how to query an XML file using LINQ (Language INtegrated Query) in Visual Studio 2008 Beta 2.

First, we need an XML file. I have chosen a very simple XML sample from MSDN samples. You can find it here.

Then, open Visual Studio 2008 Beta 2 and create a Console Application (File -> New Project -> Console Application). You can observe that there is no need to add any assembly containg LINQ classes as it is already contained in the References:

Then add the XML sample to an XML file included in the project (Solution Explorer -> Right click on project name -> Add -> New Item -> XML File -> books.xml).   

Do not forget to modify Copy to output directory property of the books.xml to Copy always. 

Open Program.cs and add using System.Xml.Linq; to the top of the file.

Finally, start querying the XML using LINQ:

The  first step is to declare a System.Xml.Linq.XElement class and load the XML from books.xml. Once we have an XElement we can use it to navigate through the XML document. For navigating through nested elements I have used the Descendants method. The from clause specifies a data source. The variable c represents an node in XML document. The where clause specifies a condition for selecting from the data source.

Here are some samples of how we can use LINQ to get different data from the XML document:

1. Get all XML nodes named “book”

var query = from c in xElement.Descendants(“book”)

                  select c;

foreach (var q in query)

{

      Console.WriteLine(q);

}

2. Get all book titles

var query = from c in xElement.Descendants(“book”)

                  select c.Element(“title”).Value;

foreach (var q in query)

{

      Console.WriteLine(q);

}

3. Get all books for which the description contains XML keyword and show the author and the title:

var query = from c in xElement.Descendants(“book”

                  where c.Element(“description”).Value.Contains(“XML”

                  select c;

foreach (var q in query)

     Console.WriteLine(q.Element(“author”).Value + “-” + q.Element(“title”).Value);

}

4. Get all books that have the price less then 10

var query = from c in xElement.Descendants(“book”)

                  where double.Parse(c.Element(“price”).Value) < 10

                  select new { author = c.Element(“author”).Value, title = c.Element(“title”).Value };

foreach (var q in query)

{

    Console.WriteLine(q.author + “-” + q.title);

}

5. Get the value of the books per author

var query = from c in xElement.Descendants(“book”)

                  group c by c.Element(“author”).Value into g

                  select new { author = g.Key, total = g.Sum(c => double.Parse(c.Element(“price”).Value)) };

foreach (var q in query)

{

     Console.WriteLine(q.author + ” - “ + q.total);

}

You can download the project from here: ConsoleApplicationLinq.zip (28.23 kb)

Related posts:

  1. C# 3.0: Linq to Xml Object Model The Linq to Xml object model is very simple. The main...
  2. C# 3.0: Writing XML Documents using LINQ Consider that we want to create the following XML...
  3. C#: Cum comparam o variabila cu NaN (Not-a-Number) Sa presupunem ca avem o secventa de cod de genul: try...
  4. Here’s what you as a programmer need to know about LINQ How much do you know about LINQ? If you...
  5. Free Microsoft Press E-Book Offer: ‘Microsoft Visual C# 2008 Express Edition: Build a Program Now!’ Microsoft Press is now giving away “Microsoft Visual C#...