C# - How to deserialize a list of strings using the DataContractSerializer with ReadObject

I found many examples on how to do this around the internet:

But none of them worked for me, so I thought I would leave an example of a working exampel of what I ended up with. I wanted to deserialize some XML that had a list of elements with just a string as inner XML, a made up example would look like:

<?xml version="1.0" encoding="utf-8" ?>
<model>
	<person>
		<name>Peter</name>
		<lastname>Rasmussen</lastname>
		<programminglanguages>
			<programminglanguage>C#</programminglanguage>
			<programminglanguage>Javascript</programminglanguage>
			<programminglanguage>Java</programminglanguage>
		</programminglanguages>
	</person>
</model>

The list of strings this revolves around is the programminglanguages element and its children. In order to Serialize the above I created the following DataContract model:

[DataContract(Name = "model", Namespace = "")]
public class Model
{
    [DataMember(Name = "person")]
    public Person Person { get; set; }
}

[DataContract(Name = "person", Namespace = "")]
public class Person
{
    [DataMember(Name = "name", Order = 0)]
    public string Name{ get; set; }

    [DataMember(Name = "lastname", Order = 1)]
    public string LastName { get; set; }

    [DataMember(Name = "programminglanguages", Order = 2)]
    public MyList ProgrammingLanguages { get; set; }
}

[CollectionDataContract(ItemName = "programminglanguage", Namespace ="")]
public class MyList : List<string> { }

The interesting parts in the above is the creation of the MyList class which uses the CollectionDataContract attribute and inherits the List class. Everything else is standard DataContract and DataMember attributes matching the XML. The above can be deserialized with the following lines of code:

using (XmlReader reader = XmlReader.Create("Model.xml"))
{
    DataContractSerializer serializer =
        new DataContractSerializer(typeof(Model));
    var model = (Model)serializer.ReadObject(reader);
}

In the above I read the XML from a file using XmlReader.Create("Model.xml"), instantiate the DataContractSerializer with my Model class and call the ReadObject method to deserialize the XML into and object.

As an alternative to using the DataContractSerializer you can use the XMLSerializer, see the differences between the two here.

It took me a while to get this right, I hope it helps you! Please leave a comment if it did!