Categories: XML, XPath Expression
Extension Method Example...
C# 3.0 added a cool feature to the toolkit called Extension Methods. Extension Methods are an extremely simple yet very powerful feature that allows you to bolt on additional method to existing objects without directly modifying those objects.
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…
XML and XPath expression examples
Given the following XML schema...

Here are a few XPath expressions and the nodes selected.
Select all child nodes…
/familytree/parent/child

Select child node element with name (attribute) of Sam
/familytree/parent/child[@name="Sam"]

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

In .NET, you can use either the XmlDocument or XPathNavigator objects to execute XPath expression in .NET framework code.
XmlDocument code samples…

For improved performance use XPathDocument...

XPath Expressions are a bit cryptic and only get worse as the complexity of your expression increases. For that reason, I highly recommend using the new LINQ to XML features in .NET.
LINQ queries are easier to read than complicated XPath expressions and perform just as well or better than using XmlDocument and XPathDocument objects.
Convert DataTable to XML
The ADO.NET DataSet object has a method for retrieving the XML representation of the data in string format called "GetXml()".
A DataTable object however, does not. Here is a small function to quickly convert the DataTable contents to an XML string.

This function uses the DataTable's WriteXml function to write its contents into the StringWriter where the ToString() method gives us the XML string representation.
The result string will look like this.

It is relatively trivial then to load the string into and XmlDocument or XPathNavigator object.