24.1. XML Object Model

If you have ever worked with XML in .NET, you will recall that the object model isn't as easy to work with as you would imagine. For example, in order to create even a single XML element you need to have an XmlDocument.

Dim x as New XmlDocument

As you will see when we start to use LINQ to query and build XML, this object model doesn't allow for the inline creation of elements. To this end, a new XML object model was created that resides in the System.Xml.Linq assembly presented in Figure 24-1.

Figure 24.1. Figure 24-1

As you can see from Figure 24-1, there are classes that correspond to the relevant parts of an XML document: XComment, XAttribute, and XElements. The biggest improvement is that most of the classes can be instantiated by means of a constructor that accepts Name and Content parameters. In the following C# code, you can see that an element called Customers has been created that contains a single Customer element. This element, in turn, accepts an attribute, Name, and a series of Order elements.

XElement x = new XElement("Customers", new XElement("Customer", new XAttribute("Name","Bob Jones"), new XElement("Order", new XAttribute("Product", "Milk"), new XAttribute("Quantity", 2)), new XElement("Order", new XAttribute("Product", "Bread"), new XAttribute("Quantity", 10)), new XElement("Order", new XAttribute("Product", ...

Get Professional Visual Studio® 2008 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.