LINQ to XML

If you would like the output of your work to go to an XML document rather than to a SQL database, all you need to do is create a new XML element for each object in the Customer table and a new XML attribute for each property representing a column in the table. To do this, you use the LINQ to XML API.

Note that this code takes advantage of the new LINQ to XML classes, such as XAttribute, XElement, and XDocument. Working with XAttributes is very similar to working with standard XML elements. However, note that XAttributes are not nodes in an XML tree; rather, they are name/value pairs, each of which is associated with an actual XML element. This is also quite different from what programmers are used to when working with the DOM.

The XElement object represents an actual XML element and can be used to create elements. It interoperates cleanly with System.XML and makes for a terrific transition class between LINQ to XML and XML itself.

Finally, the XDocument class derives from XContainer and has exactly one child node (you guessed it: an XElement). It can also have an XDeclaration, zero or more XProcessingInstructions and XComments, and one XDocumentType (for the DTD), but that's more detail than you need.

In Example 9-10, you're going to create some XElements and assign some XAttributes. This should be very familiar to anyone comfortable with XML, and a relatively easy first glimpse for those who are totally new to raw XML.

Example 9-10. Constructing an XML document using LINQ ...

Get Programming .NET 3.5 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.