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>