CSharpFeeds - All your C# feeds in one place.

Sponsors

Monday, January 08, 2007

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

by fmarguerie via Fabrice's weblog on 1/8/2007 10:12:00 AM

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
email it!bookmark it!digg it!

Original Post: Converting a CSV file to XML using LINQ to XML and Functional Construction

Subscribe

New Feed

Product Spotlight

Recently Updated Sources

Legal Note

The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.

Advertise with us