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:
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.
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:
The key point of the query is the xml node access through the statement:
It’s also interesting to note how LINQ allow us to fill a class directly with query results:
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.