C# - How to use the DataContractSerializer to serialize or deserialize XML

One way to deserialize XML is using the DataContractSerializer. You can read XML and deserialize it into an object or serialize an object into XML. If we have the following XML:

<?xml version="1.0" encoding="utf-8" ?>
<model>
	<person>
		<name>Peter</name>
		<lastname>Rasmussen</lastname>
	</person>
</model>

We can make a DataContract model that matches this XML:

[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; }
}

In the above we create matching classes for the XML. The DataContract and DataMember have matching names for the XML. The Order is needed for this as without it, the DataContractSerializer expect the properties to be ordered.

Using the above we can deserialize the XML into an object:

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

The XmlReader.Create part reads the XML from a file called Model.xml.

Serialising an object into a XML string

Alternatively we can create an object and have that serialized into a string:

var model = new Model
{
    Person = new Person
    {
        Name = "Peter",
        LastName = "Rasmussen"
    }
};

DataContractSerializer serializer =
    new DataContractSerializer(typeof(Model));
using var output = new StringWriter();
using (var writer = new XmlTextWriter(output) { Formatting = Formatting.Indented })
{
    serializer.WriteObject(writer, model);
    var xml = output.GetStringBuilder().ToString();
}

In the above we instantiate the Model object with the values from the previous XML. We then use no less than a StringWriter, XmlTextWriter and the DataContractSerializer to turn this into an XML string.

That is it

An alternative to the DataContractSerializer is the xmlserializer, which might seem simpler to use an more intuitive if you only need to work with XML.

I hope you found this helpful! If or if not, please leave a comment down below!