February 28, 2021
Hot Topics:

Converting Data to XML with LINQ to XML

  • By Paul Kimmel
  • Send Email »
  • More Articles »

The XML document is constructed on the line that begins with Dim doc as XDocument. The return type of the single statement is an XDocument (an XML document). The XDocument constructor is overloaded. One of its definitions is to accept a ParamArray of objects. The idea here is that it is unknown how many actual arguments any particular document might require. In the statement in Listing 1 the XDocument is constructed with two arguments, an XDeclaration and an XElement. The XDeclaration contains the XML document's metadata, and the XElement defines the root node, "Customers". Each of the table rows represents a Customer as defined, and each Customer is a child node of the root, Customers. Only data that is part of the collection needs to be in the LINQ query.

The individual customer nodes are constructed using a LINQ query and represent ParamArray arguments to the XElement that represents the Customers node. The From clause of the LINQ query defines the range variable cust. The range variable is like the iterator variable in a for loop. The In clause contains the data source, in this case a collection of table rows. The Order By clause sorts the results by CompanyName.

Finally, the projection--the Select clause--creates an XML element for each column in the Customer table. The XAttribute class will create an attribute from the CustomerID of the Customer row, and all of the other elements are child nodes of the Customer node. It's a bit of a complicated statement, but the statement that creates the XDocument is a single statement. If you look at the output in Listing 2 you will see that the organization of the construction statement mirrors the output.


One of capabilities of LINQ to XML is functional construction of an XML document. By using class constructors in the System.Xml.Linq namespace and LINQ queries you can iterate over data, like a database table, and construct an XML document in a single statement.


Paul Kimmel is the VB Today columnist for CodeGuru.com and has written several books on object-oriented programming and .NET. Check out his upcoming book Professional DevExpress ASP.NET Controls (from Wiley) now available on Amazon.com and fine bookstores everywhere. Look for his upcoming book Teach Yourself the ADO.NET Entity Framework in 24 Hours (from Sams). You may contact him for technology questions at pkimmel@softconcepts.com. Paul Kimmel is a Technical Evangelist for Developer Express, Inc, and you can ask him about Developer Express at paulk@devexpress.com and read his DX blog at http://community.devexpress.com/blogs/paulk.

Page 2 of 2

This article was originally published on October 5, 2009

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date