How to serialize/deserialize simple classes to XML and back
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开发者_StackOverflow 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.
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);
}
Just mark up what you want to serialize with [XmlElement(name)] (or XmlAttribute, XmlRoot, etc) and then use the XmlSerializer. If you need really custom formating, implement IXmlSerializable.
精彩评论