Getting Started with LINQ to XML

As Rob points out (I actually noticed his post on the Dev Center today!) there are some How-Do-I videos available for Visual Studio 2008. One of the videos is an overview of LINQ to XML (sorry I can’t give you a direct link to the video as they are wrapped up into some nifty Silverlight control — just scroll the videos until you see it.) Chris Pels does a pretty basic intro into XML programming with Visual Basic but a couple things that I particularly love about XML programming in Visual Basic were omitted, namely embedded expressions and XML IntelliSense. It’s really really easy to use these features too. So first watch the video and then come back here and I’ll walk you through what I would have showed next. (UPDATE: The video links are gone, check out this one instead: How Do I: Get Started with LINQ to XML?)

Embedded Expressions

So here we’ve got an XDocument created from pasting an XML literal directly into the editor:

Dim contactlist1 = <?xml version=1.0 encoding=utf-8?>

                   <contacts>

                       <contact>

                           <lastname>Davolio</lastname>

                           <firstname>Nancy</firstname>

                           <state>WA</state>

                           <phone>(206) 555-9857</phone>

                       </contact>

                       <contact>

                           <lastname>Buchanan</lastname>

                           <firstname>Steven</firstname>

                           <state>CA</state>

                           <phone>(925) 555-4848</phone>

                       </contact>

                       <contact>

                           <lastname>Suyama</lastname>

                           <firstname>Michael</firstname>

                           <state>CA</state>

                           <phone>(925) 555-7773</phone>

                       </contact>

                       <contact>

                           <lastname>Callahan</lastname>

                           <firstname>Laura</firstname>

                           <state>WA</state>

                           <phone>(206) 555-1189</phone>

                       </contact>

                   </contacts>

 

What’s really interesting is that you can create embedded expressions using the <%= %> syntax and any VB code can be placed in there. For instance, this will place the current date and time in the lastUpdated attribute:

Dim contactlist2 = <?xml version=1.0 encoding=utf-8?>

                   <contacts lastUpdated=<%= Now() %>>

                   </contacts>

The possibilities are endless, really. You can create XML by embedding a LINQ query, like LINQ to SQL, into your literal. For instance this example will select all the employees from the employee table and construct an XDocument:

Dim contactlist3 = <?xml version=1.0?>

                   <contacts>

                       <%= From employee In db.Employees _

                           Select <contact>

                                      <lastname><%= employee.LastName %></lastname>

                                      <firstname><%= employee.FirstName %></firstname>

                                      <state><%= employee.Region %></state>

                                      <phone><%= employee.HomePhone %></phone>

                                  </contact> %>

                   </contacts>

 

 

But what I really love is the fact you can easily transform any piece of XML into any other piece by embedding a LINQ to XML query. Say good-bye to XSLT! (Thank heavens because every time I looked back at my templates and style sheets it took me an hour just to remember what the heck I was doing. I hate XSLT because it’s so not intuitive — at least to me <g>). 

Transformations in VB become very intuitive because they are logically top-down and there is really no API calls to remember. For instance we can transform the contactlist1 (or contactlist3) above to produce a different document. Let’s say we only want the California contacts:

Dim contactlist4 = <?xml version=1.0 encoding=utf-8?>

                   <contacts>

                       <%= From contact In contactlist1…<contact> _

                           Where contact.<state>.Value = “CA” _

                           Select contact %>

                   </contacts>

This will result in the following XML document:

<?xml version=”1.0″ encoding=”utf-8″?>

<contacts>

  <contact>

    <lastname>Buchanan</lastname>

    <firstname>Steven</firstname>

    <state>CA</state>

    <phone>(925) 555-4848</phone>

  </contact>

  <contact>

    <lastname>Suyama</lastname>

    <firstname>Michael</firstname>

    <state>CA</state>

    <phone>(925) 555-7773</phone>

  </contact>

</contacts>

 

Or let’s say we needed to transform this a bit more into a different structure:

Dim contactlist5 = <?xml version=1.0 encoding=utf-8?>

                   <employees>

                        <%= From contact In contactlist1…<contact> _

                            Where contact.<state>.Value = “CA” _

                            Select <employee>

                                      <%= contact.<lastname> %>

                                      <%= contact.<firstname> %>

                                      <region><%= contact.<state>.Value %></region>

                                   </employee> %>

                   </employees>

 

This transformation will produce the following XML document:

<?xml version=”1.0″ encoding=”utf-8″?>

 

<employees>

  <employee>

    <lastname>Buchanan</lastname>

    <firstname>Steven</firstname>

    <region>CA</region>

  </employee>

  <employee>

    <lastname>Suyama</lastname>

    <firstname>Michael</firstname>

    <region>CA</region>

  </employee>

</employees>

 

You can even take fragments and do anything you want with them, even merge them together. A fragment is just an XElement:

Dim contactlist6 = <contacts>

                       <contact>

                           <lastname>Massi</lastname>

                           <firstname>Beth</firstname>

                           <state>CA</state>

                           <phone>(925) 555-1212</phone>

                       </contact>

                   </contacts>

 

We can take this and easily merge it into another fragment, for example:

 

Dim contactlist7 = <CApeople>

                       <contacts>

                           <%= From contact In contactlist1…<contact> _

                               Where contact.<state>.Value = “CA” _

                               Select contact %>

                       </contacts>

                       <beth>

                           <%= From beth In contactlist6…<contact> _

                               Select beth.<lastname> %>

                       </beth>

                   </CApeople>

 

This will produce the following XML fragment:

 

<CApeople>

  <contacts>

    <contact>

      <lastname>Buchanan</lastname>

      <firstname>Steven</firstname>

      <state>CA</state>

      <phone>(925) 555-4848</phone>

    </contact>

    <contact>

      <lastname>Suyama</lastname>

      <firstname>Michael</firstname>

      <state>CA</state>

      <phone>(925) 555-7773</phone>

    </contact>

  </contacts>

  <beth>

    <lastname>Massi</lastname>

  </beth>

</CApeople>

 

 

Okay so you’re probably thinking, “that’s awesome, gimme!” (At least I hope you are <g>) But, wait! There’s more!

 

XML IntelliSense

What would Visual Basic be without IntelliSense? Even XML in Visual Basic can provide IntelliSense, however you have to let VB know the schema of the XML data your working with. To do that just add your XML document into the project and then on the XML menu select “Create Schema”:

This will create an XSD file by inferring the schema. You then need to locate this file and include it into your project. However, there’s this nifty little tool called the XML to Schema Tool that you can download which installs a New Item template called “XML to Schema” that makes this process much easier. It can infer a schema from an XML resource on the web, a literal pasted from the clipboard, or a file on disk, and then it automatically adds the XSD file to your project in one step.

Now that we’ve got a schema we can start typing away back in our code and we get IntelliSense on our XML:

Visual Basic also handles XML namespaces by including an Imports statement at the top of the code file. This way you can work with multiple namespaces in a project.

Well I hope this gives you a good introduction to XML in Visual Basic. There’s just so much you can do with this language feature it’s impossible to show you all the possibilities. Look for some How-Do-I videos soon!

Enjoy,
-B