LINQ: serialize C# classes

The version 3.5 of Microsoft’s .NET Framework introudced the LINQ (Language Integrated Query).component.

LINQ is a SQL-like language that allows to query different source of data, as objects, xml files and databases.

What i’ll show today is how to generate an xml rappresentation of a C# class instance..

Suppose to have a C# class Book so defined.

1
2
3
4
5
6
public class Book
{
  public String title { get; set; }
  public String author { get; set; }
  public String editor { get; set; }
}

Now we define and populate a list of books:

1
2
3
4
5
6
7
8
9
10
11
12
13
List<book> lstBooks = new List<book>();

Book l1 = new Book();
l1.author = "Alessandro Manzoni" ;
l1.title = "I Promessi Sposi";
l1.editor= "Mondadori";
lstBooks.add(l1);

Book l2 = new Book();
l1.author = "Dante Alighieri" ;
l1.title = "La Divina Commedia";
l1.editor= "ERGA Edizioni";
lstBooks.add(l2);

Once we have the list we can use this LINQ code to obtain a consistent XML rappresentation:

1
2
3
4
5
6
7
8
9
10
var lstXML = new XDocument(
    new XElement("Books",
      from p in lstBooks
      select new XElement("Book",
        new XElement("title", p.title),
        new XElement("author", p.author),
        new XElement("editor", p.editor),
      )
    )
  );

Finally look at the content of lstXML. It’s exactly the xml string we expect!

1
2
3
4
5
6
7
8
9
10
11
12
<books>
  <book>
    <title>I Promessi Sposi</title>
    <author>Alessandro Manzoni</author>
    <editor>Mondadori</editor>
  </book>
  <book>
    <title>La Divina Commedia</title>
    <author>Dante Alighieri</author>
    <editor>ERGA Edizioni</editor>
  </book>
</books>

Tags: , , ,


About Claudio

Claudio Marai is a co-founder of DevInterface.

After graduating in Computer Science has contributed to develop complex web applications based on Java/J2EE and desktop applications with the. NET framework for the Ministry of Justice and ultimately for the banking ambit.

The passion for web in recent years has led him to be interested in more modern frameworks such as Ruby on Rails and Django, and to a development approach based on agile methodologies such as eXtreme Programming and SCRUM.

About DevInterface

We are an information and communication technology agency. Our mission is to provide web application development, design services and communication strategies. We specialize in building web applications with modern and efficient frameworks.

Related Post

Leave a Reply

Insert code beetween <code lang="ruby"> and </code>

Copyright 2012 DevInterface s.n.c.

DevInterface Blog is proudly powered by WordPress