24.2. Creating XML with LINQ

While creating XML using the new object model is significantly quicker than previously possible, the real power of the new object model comes when you combine it with LINQ in the form of LINQ to XML (XLINQ). By combining the rich querying capabilities with the ability to create complex XML in a single statement, you can now generate entire XML documents in a single statement. Let's continue with the same example of customers and orders. In this case we have an array of customers, each of whom has any number of orders. What we want to do is create XML that lists the customers and their associated orders. We'll start by creating the customer list, and then introduce the orders.

To begin with, let's create an XML literal that defines the structure we want to create.

Dim customerXml = <Customers>
                      <Customer Name="Bob Jones">
                      </Customer>
                  </Customers>

Although we can simplify this code by condensing the Customer element into <Customer Name="Bob Jones" />, we're going to be adding the orders as child elements, so we will use a separate closing XML element.

24.2.1. Expression Holes

If we have multiple customers, the Customer element is going to repeat for each one, with Bob Jones being replaced by different customer names. Before we deal with replacing the name, we first need to get the Customer element to repeat. You do this by creating an expression hole, using a syntax familiar to anyone who has worked with ASP:

Dim customerXml = <Customers> <%= From c ...

Get Professional Visual Studio® 2008 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.