LINQ offers an API called LINQ to XML, formally known as XLinq, that provides support for working with XML. This API resides in the System.Xml.Linq namespace, and you need to add a reference to the assembly with the same name to be able to use it. If you installed the Orcas March CTP bits, the assembly can be found in folder C:\Windows\Microsoft.NET\Framework\v3.5.20209.

In the namespace you can find classes such as XNode, XElement, XAttribute, XText, etc.

XElement implements an XML element. It has several constructor. The following snippet constructs an empty element called winner.

The output is

Overloaded constructor can take additional parameters. If we pass a string:

We get:

We can also pass an XAttribute


In this case the winner element will have an attribute called Year having the value 1999, and the text of the element will be Manchester Utd..

We can nest the all these to make a hierarchy of xml elements:

Of course, the XML elements don’t have to be created like that. They can be dynamically created. One way is using methods like Add, AddFirst, RemoveNodes, etc., methods from the XContainer class.

And we can write this to a file with:

However, LINQ to XML offers a better way to generate XML content.

The result in this case is the same as above.

XElements has several overloads for saving its content to a file:

On the other hand, XElement offers several overloaded static methods for loading content from XML files:

The following code loads the content of the file winners.xml and prints it in the console.

Considering that we have in winners.xml the list of UEL winners, we can load the content of this XML file and create Winner objects:

XElement.Load() creates an XElement containing all the elements in the file. Elements() returns only the children called winner (in our case all the children elements of the root). After that we project Winners created by accessing the children of element “winner” in the XML file. The output is

Now suppose you want to project only the names of the winners. In this case we could write:

The ouput of the program is:

This output however lists a team multiple times. If we want to have these winners listed only once we could apply the Distinct operator on the result and select the winners only once:

The new output would be

1 Comment on "LINQ to XML"

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.