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

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" ?>
<name>Harry Potter</name>

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))

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! 🙂

Comments (1)

  1. Tyler Fang says:

    Update on this:

    Do not try to refactor out the textReader.MoveToContent() checks into one single condition statement. And the reason is MoveToContent() drives the iterator to move forward and read in next node. Thus, apparently, it matters that the elements in xml need to be in correct order so the can be collected properly.

    I shall figure out a more flexible version of this later.

Skip to main content