Sometimes I want to emulate stored data of my classes without setting up a round trip to the database. For example, let's say I have the following classes:
public class ShoppingCart
{
public List<CartItem> Items {get; set;}
public int UserID { get; set; }
}
public class CartItem
{
public int SkuID { get; set; }
public int Quantity { get; set; }
public double ExtendedCost { get; set; }
}
Let's say I build a ShoppingCart
object in memory and want to "save" it as an XML document. Is this possible via some kind of XDocument.CreateFromPOCO(shoppingCart)
method? How about in the other direction: is there a built-in way to create a ShoppingCart
object from an XML document like new ShoppingCart(xDoc)
?
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.