Fabrice's weblog

Tools and Source

News


Read sample chapters or buy LINQ in Action now!
Our LINQ book is also available on AMAZON

.NET jobs

Emplois .NET

The views expressed on this weblog are mine alone and do not necessarily reflect the views of my employer. The content of this weblog is independent from Microsoft or any other company. transatlantys hot news

Contact

Me

Others

Selected content

Converting a CSV file to XML using LINQ to XML and Functional Construction

Steve has published on his blog a sample from the book we are working on together. This example shows how LINQ to XML makes it easy to convert a CSV file into an XML document.

Going from CSV to XML doesn't require something more complicated than this:

XElement xml =
  new XElement("books",
    from line in File.ReadAllLines("books.txt")
    where !line.StartsWith("#")
    let items = line.Split(',')
    select new XElement("book",
      new XElement("title", items[1]),
      new XElement("authors",
        from authorFullName in items[2].Split(';')
        let authorNameParts = authorFullName.Split(' ')
        select new XElement("author",
          new XElement("firstName", authorNameParts[0]),
          new XElement("lastName", authorNameParts[1])
        )
      ),
      new XElement("publisher", items[3]),
      new XElement("publicationDate", items[4]),
      new XElement("price", items[5]),
      new XElement("isbn", items[0])
    )
  );

If you haven't taken a look at LINQ to XML before, let's bet that this short example will entice you to!

Cross-posted from http://linqinaction.net

Comments

WildHeart said:

"Going from CSV to XML doesn't require something more complicated than this". Oh, it does... Your sample doesn't support fields wrapped in quotes which might contain the separtor (line.Split would create more fields than required in this case)... Real life CSVs are a bit trickier...

# January 8, 2007 8:01 AM

UglyBear said:

You could easily make this work with fields that may contain a comma, and tab delimited values, etc., by using the LINQ to CSV library at

www.codeproject.com/.../LINQtoCSV.aspx

# April 11, 2008 7:56 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)