LINQ to XML

If you would like the output of your work to go to an XML document rather than to a SQL database, you have only to create a new XML element for each object in the Customers 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, as illustrated in Example 15-6.

Note carefully that this code takes advantage of the new LINQ to XML classes, such as XElement, XAttribute, and XDocument. Working with XAttributes, for example, is very similar to working with standard XML elements. However, note carefully that, for example, XAttributes are not nodes in an XML tree, but instead are name/value pairs associated with an actual XML element. This is also quite different from what you are used to in 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, XComments, and one XDocumentType (for the DTD), but that is more detail than we need.

In the next example, we'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 (see ...

Get Programming C# 3.0, 5th Edition 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.