Thursday, August 30, 2007
A while back I posted an example of how to convert a comma seperated file (CSV) to XML using LINQ to XML and functional construction.  We're in the final push to get LINQ in Action to production and as such I've been spending a lot of time going back through the chapters cleaning things up, as well as making sure both a C# and VB.NET example is provided for every code sample presented in the book.  Tonight I was converting a code sample from Chapter 12 that shows how to convert a CSV file to XML using LINQ to XML.  While the C# code is very nice, I like the VB version that is shown below even better.

Imports System.IO
Imports System.Xml.Linq

Module FlatFileToXmlWithXmlLiterals
  Sub Main()
    Dim xml As XElement = <books>
                          <%= From line In File.ReadAllLines("books.txt") _
                          Where Not line.StartsWith("#") _
                          Let items = line.Split(",") _
                          Select _
                          <book>
                            <title><%= items(1) %></title>
                            <authors>
                              <%= From authorFullName In items(2).Split(";") _
                                Let authorNameParts = authorFullName.Split(" ") _
                                Select <author>
                                         <firstName><%= authorNameParts(0) %></firstName>
                                         <lastName><%= authorNameParts(1) %></lastName>
                                       </author> _
                              %>
                            </authors>
                            <publisher><%= items(3) %></publisher>
                            <publicationDate><%= items(4) %></publicationDate>
                            <price><%= items(5) %></price>
                            <isbn><%= items(0) %></isbn>
                          </book> _
                        %>
                      </books>

    Console.WriteLine(xml)
  End Sub
End Module

As an aside, if you've been meaning to learn about LINQ, or if you've already begun your journey, now is a great time to checkout the early access edition of LINQ in Action.  We have every chapter available for download, and will very shortly be making the source code available.  We still have a little ways to go, but we're getting close!

Download the sample project here: Chapter12.FlatFileToXml.Vb.zip (10.09 KB)
Friday, August 31, 2007 1:26:49 AM (Eastern Daylight Time, UTC-04:00) | Comments [0] |  |  |  | #
Tracked by:
"New and Notable 186" (Sam Gentile) [Trackback]
"Consumer Electronics Reviews" (Consumer Electronics Reviews) [Trackback]
"New and Notable 186" (Sam Gentile's Blog) [Trackback]
"New and Notable 186" (Sam Gentile's Blog) [Trackback]
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

Search
Archive
Links
Categories
Admin Login
Sign In
Blogroll
Themes
Pick a theme: