1. Home
  2. Computing & Technology
  3. Visual Basic

LINQ to XML - Microsoft's latest and greatest!

By Dan Mabbutt, About.com

Jun 21 2008

I've saved the best for last. LINQ - Language INtegrated Query is a technology just introduced in the latest 2008 versions of Visual Basic. LINQ is a bit like SQL, but it can do so much more because it's built in, not called in, with .NET languages that use the 3.5 version of the Framework. As a result, you can LINQ to XML, to Objects, to ADO.NET, to XML, even to SQL itself.

Since it is built in, the different language implementations of LINQ are also different. Visual Basic is clearly (a-hem!) superior because it includes support for handy tools like XML literals and XML Axis. These things are not available in C#. (At break time, the C# programmers can be found roasting and then grinding their own beans for coffee. The C++ programmers also grow their own beans.)

But since it is, well, LINQ to XML, the end result is an XML file. I think this qualifies as "simple" file processing because XML files are simple to use and understand, especially with LINQ.

To start with, let's create an XML file using LINQ. I've decided to create something like an XML version of the Win.Ini file we saw earlier. Here's the code that does it:

FileName = "WinIni.xml"
Dim WinIniXML As XElement = _
   <winini>
      <mail>
         <mapi>1</mapi>
      </mail>
      <mciextensions>
         <m2v>MPEGVideo</m2v>
      </mciextensions>
   </winini>
WinIniXML.Save(FileName)

Notice how the XML is included as a data type, just the way it would be found in a file. This is an XML literal. Here's what is written to the file:

<?xml version="1.0" encoding="utf-8"?>
<winini>
   <mail>
   <mapi>1</mapi>
   </mail>
   <mciextensions>
   <m2v>MPEGVideo</m2v>
   </mciextensions>
</winini>

Reading the file is just as easy and shows off how to use XML axis. Heres the code:

FileName = "WinIni.xml"
Dim WinIniXML = XElement.Load(FileName)
Console.WriteLine(WinIniXML.ToString)
Console.WriteLine(WinIniXML.<mail>.<mapi>.Value)
Console.WriteLine(WinIniXML.<mciextensions>.<m2v>.Value)

The first WriteLine displays the whole XML document. The second and third show how easy it is to access the content of the XML elements. These two lines display:

1
MPEGVideo

This power in programming should tell you why XML is replacing all the old configuration files.

Explore Visual Basic
By Category
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Visual Basic
  4. Using VB.NET
  5. Simple File Processing and VB.NET

©2009 About.com, a part of The New York Times Company.

All rights reserved.