[C#] A quick (and easy) way to deserialize a XML file into List

I spent more time than I expected to find a easy and intuitive way to quickly transform the data contained by a XML file into a List object in C#. And here it is:

 

Suppose you have a XML file which looks like following:

 <?xml version="1.0" encoding="utf-8" ?>
 <list>
 <title>FeaturedMovies</title>
 <movie>
 <name>Grey</name>
 </movie>
 <movie>
 <name>Haywire</name>
 </movie>
 <movie>
 <name>Harry Potter</name>
 </movie>
 </list>

Ideally after parsing, we should have a list of objects which simply contains a string filed, the "name". There are no attributes involved in this file, just for the purpose of demonstrating the simplest case. Here's the code that will properly decode it:

  using System;
 using System.Xml;
 using System.Collections.Generic;
  class Movie
 {
 public string name;
 public string searchToken;
 public string guid;
 }
 static void Main(string[] args)
 {
 XmlTextReader textReader = new XmlTextReader("C:\\MoviesList.xml");
 
 List<Movie> movieList = new List<Movie>();
 
 while (textReader.Read())
 {
 Movie movie = new Movie();
 
 if (textReader.MoveToContent() == XmlNodeType.Element && textReader.Name == "name")
 movie.name = textReader.ReadElementString();
 if (textReader.MoveToContent() == XmlNodeType.Element && textReader.Name == "searchToken")
 movie.searchToken = textReader.ReadElementString();
 
 if (!String.IsNullOrEmpty(movie.name))
 movieList.Add(movie);
 }
 }
 

You might notice that none of the movies in the XML actually have a "searchToken", while this will still work fine. But since we want the "name" to be mandatory, we do check for it before adding that into the list.

 

Hope this will save you sometime! :)