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:
4 Responses
Brent
February 14th, 2008 at 9:17 am
1This is great. Any recommendations on how to remove a node when looping through the results of this query method. Using the following leaves and empty, self closing element instead of deleting the entire node:
q.Elements().Remove();
I’ve tried a few variations within the foreach loop, but all leave the empty self-closing element. When referencing the root node, an entire node is removed correctly (or as I desire), but this doesn’t help me since I want to delete a specific book, not the first one in the file:
xElement.Element(”Book”).Remove();
(this is how MSDN says to do it
http://msdn2.microsoft.com/en-us/library/bb308960.aspx)
Any help would be much appreciated. This problem is really holding up my progress on a project!
Ankh
May 28th, 2008 at 4:32 am
2great article! just what i needed
mary
September 27th, 2008 at 4:44 am
3Hi great article… but i have many questions about if a can use something like this
from c in xElement.Descendants(”book”), b in XElement.Descendants(”years”)
where c.Element(”author”).Value = “Pablo Cohelo”
and b.Element(”id”).Value = 5
select c.Element(”price”).Value
if you have some tutorial or anything could help me!!
THANKS
Ashotosh Das
February 19th, 2009 at 5:14 pm
4Great article and thanks for ur hard work
RSS feed for comments on this post · TrackBack URI
Leave a reply
Categories
Subscribe
Sponsors
Latest Posts
Links
Meta
Adrian Roman is proudly powered by WordPress - BloggingPro theme by: Design Disease