LINQ: from xml to C# classes

I continue my post on LINQ and C# programming talking about the conversion from XML file to C# classes.

Previously I’ve show how to serilize a C# class into XML file.

Let me show you an example.

Suppose we have an XML file that contains the list of Italian municipalities with their area code.

We now want to load this file into a list of C# objects more convenient to use within our application.

Define the file Municipalities.xml as follow:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<municipalities>
  <municipality>
    <cod>045</cod>
    <description>Verona</description>
  </municipality>
  <municipality>
    <cod>02</cod>
    <description>Milano</description>
  </municipality>
  <municipality>
    <cod>06</cod>
    <description>Roma</description>
  </municipality>
  <municipality>
    <cod>011</cod>
    <description>Torino</description>
  </municipality>
  <municipality>
    <cod>055</cod>
    <description>Firenze</description>
  </municipality>

...
</municipalities>

Starting from this xml we define a Municipality class in our project and then we go to fill it with data taken from single xml node.

If you have a more complex structure you can use some class generator tool, to achieve C# class definition from xml.

But our example is simple and we prefer to define the class manually.

1
2
3
4
5
public class Municipality
{
  public String cod { get; set; }
  public String description { get; set; }
}

Now we are ready: we can take advantage of LINQ to fill a Municipality list with a single query.

Hence, look at method loadMunicipalities that execute the LINQ query:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static List loadMunicipalities(string xmlFilePath)
{
  List lstMunicipalities = new List();

  var com = from p in  XElement.Load(xmlFilePath).Elements("municipalities")
                                 .Elements("municipality")
                       orderby (string)p.Element("description") ascending
                       select new Municipality
                       {
                          cod = (string)p.Element("cod"),
                          description = (string)p.Element("description")
                       };

  foreach (var c in com)
    lstMunicipalities.Add(c);

  return lstMunicipalities;
}

The key point of the query is the xml node access through the statement:

1
XElement.Load(nomeFileXml).Elements("municipalities").Elements("municipality")

It’s also interesting to note how LINQ allow us to fill a class directly with query results:

1
2
3
4
5
6
..
 select new Municipality
  {
    cod = (string)p.Element("cod"),
    description = (string)p.Element("description")
  };

In my opinion this is the more interesting feature because, by defining once the new of the object within the query, we achieve directly an object’s list inside the variable com.

If you want, you can use the com variable in your code. But for convenience we prefer to convert it to a List with the last foreach cicle.

In addition to simplicity, it’s important to say that this approach with LINQ is also much faster in run-time compared to reading an XML file by scrolling through the nodes as XmlNode objects.

A major advantage when dealing with large XML files.

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

2 Responses to “LINQ: from xml to C# classes”

  1. Aher says:

    List -> which namespace should be reference ?
    because if using System.Collection.Generic then strong type must be specify like List

  2. Aher says:

    i mean

    1
     List<T>

Leave a Reply

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

Copyright 2012 DevInterface s.n.c.

DevInterface Blog is proudly powered by WordPress