| « Extension Method Example... | XML and XPath expression examples » |
LINQ-to-XML Examples...
In the previous post, I did some experimentation with XPath Expressions on a very simple XML file. I provided examples of XPath expressions and how to execute these expressions using XmlDocument and XPathDocument. Although powerful, XPath Expressions can come off as a bit cryptic. As your query becomes more complicated, so does the expression. XPath Expressions can get as ugly as Regular Expressions. Fortunately, starting with the .NET Framework 3.0 Microsoft introduced the Language Integrated Query (LINQ). This set of extensions to the .NET Framework provides unified methods for querying almost any type of .NET object.
Let’s take the XPath queries from the previous post and do some LINQ-to-XML instead…
Follow up:
Given the following XML schema…

Select all child nodes…
First with XPath Expression…
/familytree/parent/child

Now let’s select the same nodes with LINQ-to-XML...
Remember to add...
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;

If all we want is strings, then let’s load just strings…

Select child named Sam…
First with XPath Expression...
/familytree/parent/child[@name="Sam"]

Next with LINQ-to-XML methods…

Select distinct grandchild nodes…
First with XPath Expression…
/familytree/parent/child/grandchild[not(@name=preceding::grandchild/@name)]

Next with LINQ-to-XML methods…

A more object-oriented, LINQ version…

When choosing which technology to implement, performance always has to be considered. Since LINQ just extends existing technologies, it’s only logical that it would perform a little slower. That being said though, we’ve had some extremely good results parsing large XML files using it.