LINQ To XML

In my earlier post on LINQ, we saw an example of LINQ to Objects. In this post we will see LINQ to XML example. LINQ to XML was the real reason why i attracted towards LINQ. I’m pretty excited to see what LINQ provides as compare to the old techniques. So let’s start coding 🙂

Let’s say we have an XML as below:











Now suppose that I want to get list of all employees in Microsoft. Without LINQ, I would probably load the xml in XmlDocument object and then apply XPATH with respect to the company name attribute. With LINQ, it’s easy and simple way to load xml and write a single SQL like query even for XML. For instance i want to fetch list of all employees in KalSoft,

var companies = XElement.Load("companies.xml").Elements("Company");

var queryResult = from company in companies
where company.Attribute("Name").Value == "KalSoft"
select company.Descendants();

This query selects all the descendants i.e. Employee(s) of company having Name == “KalSoft”. To obtain the output we can get the string as

foreach (var item in queryResult)
{
foreach (var element in item)
{
Console.WriteLine(element);
}
}

which will give us the desired output:

LinqToXmlOutput

Hence, LINQ to XML provides an simpler way, to programmer, to query XML Documents based on different conditions.