Share via


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

Comments

  • Anonymous
    October 17, 2007
    Wow I can't wait for this.  I am doing a lot of XML at work lately, so I will definitely push for the upgrade becuase of the simplicity illustrated here.  Still don't quite understand the LINQ syntax but as Picasso said "What we must learn, we learn by doing". Thanks!

  • Anonymous
    October 17, 2007
    Hi Josh, I agree LINQ syntax was a bit tricky for me at first as well. Coming from a SQL background I wasn't thinking in objects so it was a bit of a transition for me. Luckily though, the query expressions are familiar, it just takes a bit of practice. Make sure you check out the How-Do-I videos on LINQ here: http://msdn2.microsoft.com/en-us/vbasic/bb466226.aspx?wt.slv=topsectionimg#linq And download Beta 2 here: http://msdn2.microsoft.com/en-us/vbasic/aa700831.aspx Enjoy! -B

  • Anonymous
    October 18, 2007
    Thanks alot!  Looking forward to downloading the beta and giving this a whirl as soon as I can get some "play" time. When it comes to familiarizing yourself with a new syntax, it makes a big difference when you are just staring at code compared to typing it up in VS and having intellisense grab you by the hand and play the "guiding light" role.  How could I ever code without it?! I'd marry intellisense if it had a sense of humor. Regards...

  • Anonymous
    October 23, 2007
    One of the things I most dearly missed from FoxPro when I moved to VB.NET was the ability to easily dump

  • Anonymous
    November 01, 2007
    We just released a new set of How-Do-I videos in our LINQ series on LINQ to XML in Visual Basic. These

  • Anonymous
    November 02, 2007
    We just released a new set of How-Do-I videos in our LINQ series on LINQ to XML in Visual Basic. These

  • Anonymous
    February 25, 2008
    Hi Beth, These are really great tutorials - especially liked the LINQ to XML ones, so thanks very much.  I'm trying to take this a little further but struggling to find any info, and wondered if you would be able to help.   What I want to do is:

  1. Open an existing Excel spreadsheet in XML form. 2. Dump my data to a named worksheet using LINQ to XML. (The easy bit after watching your tutorial)
  2. Save the output back into Excel for the users. Excel can then take care of some of the formatting and charting requirements based on my source data exported from the database. Can you give me any tips on these stages, or do I have to revert back to the Interop approach? Any ideas greatly appreciated, Thanks and Regards, Pete
  • Anonymous
    February 26, 2008
    Hi Peter, I'm not the Excel expert but you may want to take a look at the Open Office XML format that Office 2007 now supports. For instance, rename your xlsx file to zip and take a look inside. You can replace/create pieces of the Excel document since these are xml files. I have an example of how to do that with Word and the Packaging classes here: http://blogs.msdn.com/bethmassi/archive/2007/12/06/mail-merging-with-word-and-linq-to-xml-in-vb.aspx There's also a lot of great video tutorials on the Office Developer site: http://msdn2.microsoft.com/en-us/office/bb496949.aspx HTH, -B

  • Anonymous
    April 01, 2008
    hello Beth, thanks for knowledges Can I change date format from sql database to xml when using linq to xml?

  • Anonymous
    June 06, 2008
    I found the answer date=<%= Format(company.date, ("dd'/'MM'/'yyyy")) %>