Free Information Technology Magazines and eBooks

Friday, May 29, 2009

How to Load and Query XML document file using LINQ

On my previous blog posts we talked about LINQ to Object and LINQ to SQL. On this article, I will try to show you how to use LINQ to XML, formerly code-named XLinq. LINQ to XML allows querying of XML data. A new namespace in .NET 3.5 is System.Xml.Linq which contains classes for creating and querying XML trees. For todays discussion we will use XDocument class to load and query xml document file.


XDocument represents an XML document which contains the root level XML constructs, such as document type declaration (XDocumentType), root element (XElement), and comments objects (XComment).


To load and query XML document using LINQ, follow these steps:

1. Include the following namespaces on your project.

using System.Linq;
using System.Xml.Linq;


2. To load the XML document use XDocument class.

XDocument xml = XDocument.Load(@"EmployeeSample.xml");


3. Now you can parse through the loaded XML using LINQ.

var query = from p in xml.Elements("employees").Elements("employee")
where (int)p.Element("id") == 1
select p;


4. To confirm the content of the query, display it on the console.

foreach (var record in query)
{
Console.WriteLine("Employee: {0} {1}",
record.Element("firstname").Value,
record.Element("lastname").Value);
}


The complete source code to load and query xml document using LINQ:

static void Main(string[] args)
{
XDocument xml = XDocument.Load(@"EmployeeSample.xml");
var query = from p in xml.Elements("employees").Elements("employee")
where (int)p.Element("id") == 1
select p;
foreach (var record in query)
{
Console.WriteLine("Employee: {0} {1}",
record.Element("firstname").Value,
record.Element("lastname").Value);
}
}


For more LINQ coding tips, subscribe now

3 comments:

Rich said...

Very Good! This really helped me a lot. I was able to get to the information I needed and develop the solution sooner.

Thank you

Rama Charan said...

thanks for code
Font makes your post tough to read

C:/DunMiffSys said...

Most helpful LINQ post I"ve seen, imh. Thanks!