MSDN Magazine - February 2008 - (Page 26) When coding against the DOM, I’m basically trying to construct the XML tree from the inside out. It is like I have to fight against the API to get my work done. Rather than having to construct a whole bunch of nodes and connect them together in the DOM, it’d be easier if I could just express the structure of the XML and then substitute the values in-line. This is exactly what the LINQ to XML API allows me to do—I can create the XML from the top down (otherwise known as functional construction). Using LINQ, I can now write a much shorter and cleaner version of the function in Figure 2. The new, simpler solution is presented in Figure 3. This produces exactly the same output as the first solution, but, as you can see, the new snippet is shorter and much easier to read. I use the constructors for the XElement and XAttribute objects to construct the tree. And note this cool feature: these constructors have overloads that allow me to pass in additional LINQ to XML objects; for instance, I can pass an XElement into another XElement. The first line creates a new XElement and names it Customers; it also creates the related and tags. The second parameter passed into the constructor is a LINQ query that will become the contents inside these Customer tags. This query loops through all the customers in my list and transforms the results to XML. Everything after the Select statement is evaluated and at run time produces a collection of Customer elements. Since I’m querying data, I can take advantage of LINQ to do such things as filtering, sorting, grouping, joining, and a variety of other operations. For example, I could modify the function to only return Figure 3 New Solution Using LINQ Public Function ConvertToXML(ByVal custList As List(Of Customer)) As _ String Dim doc = New XElement(“Customers”, _ From cust In custList _ Select New XElement(“Customer”, _ New XAttribute(“FirstName”, cust.FirstName), _ New XAttribute(“LastName”, cust.LastName), _ New XElement(“Address”, cust.Address), _ New XElement(“City”, cust.City), _ New XElement(“State”, cust.State), _ New XElement(“ZipCode”, cust.Zip))) Return doc.ToString End Function The LINQ to XML API customers who live in Seattle by adding a Where clause to the query. If I were using the DOM to do this, I’d have to add an If statement to the For loop. Sorting the results in LINQ is now as easy as adding an Order By clause to my query. With the DOM, I would have to manually sort the results before constructing the XML. The example I’m using is fairly simple, as I am really just scratching the surface of what can be done with LINQ. So far, I’ve used the XElement and XAttribute types. The API defines many other types, including XDocument, XNamespace, and XComment. XML Literals and Embedded Expressions While LINQ to XML provides a much simpler experience than you’ve had in the past, the approach still isn’t quite as easy as it could be. This is where XML literals, a new concept introduced in Visual Basic 9.0, enters the picture. To understand XML literals, you must first understand what a literal is. Consider the following variables: Dim Dim Dim Dim someString = “A string literal” someNumber = 256 someDate = #2/27/2008# someBoolean = True Figure 4 Directly Assign Data to the Customers Variable Dim customers = 123 Main St Redmond WA 10104 456 First St Seattle WA 10028 Each of the variables shown here is directly assigned a value, and in each case the actual value is called a literal. (Note that with the new Type Inference feature in Visual Basic 9.0, these declarations are still strongly typed, even though I haven’t provided an “As ” clause for each variable.) Anything inside quotes is referred to as a string literal. And the value assigned to someDate, for example, would be a date literal. An XML literal is exactly the same concept. I can express XML exactly as I would express the data anywhere else (in its literal representation). That means no quotes around it; XML literals are not Strings. I can directly assign data to the customers variable, as shown in Figure 4, and the compiler will see that the value is literal XML. Thus, the variable’s type will be inferred to be XElement. When the compiler sees this XML, it will convert it into a series of calls to the LINQ to XML API. Not only is this easier to read, but the compiler actually optimizes this construction and produces faster code than I would get just using the API directly. So far, all I’ve done is paste some XML into my project and store it in a variable—this isn’t necessarily that useful. One common misconception about using XML support in Visual Basic 9.0 is that you should use it to store XML documents inside your code. This, however, is far from the truth. The point is to provide an easy syntax to create, query, and transform XML documents. I demonstrated how XML literals allow me to easily create documents. But in order for this to be useful, I need a way to insert values directly into the XML. This is where embedded expressions come into play. An embedded expression essentially tells the compiler to “stop processing this XML literal for a second, evaluate the expression, and insert the result back into the XML.” In order to do this, I use the syntax. Figure 5 takes my ConvertToXml function and demonstrates how I can improve it using XML literals and embedded expressions. This example uses a LINQ query to generate XML, but the data source that I am querying over is actually an in-memory collec- 26 msdnmagazine Basic Instincts
For optimal viewing of this digital publication, please enable JavaScript and then refresh the page. If you would like to try to load the digital publication without using Flash Player detection, please click here.