How to serialize/deserialize simple classes to XML and back

XmlSerializer is one way to do it. DataContractSerializer is another. Example with XmlSerializer:

using System.Xml;
using System.Xml.Serialization;

//...

ShoppingCart shoppingCart = FetchShoppingCartFromSomewhere();
var serializer = new XmlSerializer(shoppingCart.GetType());
using (var writer = XmlWriter.Create("shoppingcart.xml"))
{
    serializer.Serialize(writer, shoppingCart);
}

and to deserialize it back:

var serializer = new XmlSerializer(typeof(ShoppingCart));
using (var reader = XmlReader.Create("shoppingcart.xml"))
{
    var shoppingCart = (ShoppingCart)serializer.Deserialize(reader);
}

Also for better encapsulation I would recommend you using properties instead of fields in your CartItem class.


Nicely done. Here is the example to serialize plain POCO to string.

    private string poco2Xml(object obj)
    {
        XmlSerializer serializer = new XmlSerializer(obj.GetType());
        StringBuilder result = new StringBuilder();
        using (var writer = XmlWriter.Create(result))
        {
            serializer.Serialize(writer, obj);
        }
        return result.ToString();
    }

You could serialize/deserialize with either the XmlSerializer or the DataContractSerializer.

Annotate your classes with DataContract and DataMember attributes and write something like this to serialize to xml to a file.

ShoppingCart cart = ...
using(FileStream writer = new FileStream(fileName, FileMode.Create))
{
   DataContractSerializer ser = new DataContractSerializer(typeof(ShoppingCart));
   ser.WriteObject(writer, cart);
}