序列化是将对象状态转换为可保持或可传输的形式的过程。序列化的补集是反序列化,后者将流转换为对象。这两个过程一起保证数据易于存储和传输。
1、要序列化对象,首先需要实例化一个XmlSerializer对象,指定要序列化的对象类型,然后实例化一个流/写入器对象,以把文件写入流/文档中。最后一步是在XmlSerializer上调用Serializer()方法,给它传递流/写入器对象和要序列化的对象。
例子:
public static void SerializeProduct()
{
//new products object
var product = new Product
{
ProductID = 200,
CategoryID = 100,
Discontinued = false,
ProductName = "Serialize Objects",
QuantityPerUnit = "6",
ReorderLevel = 1,
SupplierID = 1,
UnitPrice = 1000,
UnitsInStock = 10,
UnitsOnOrder = 0
};
FileStream stream = File.OpenWrite("product.xml");
using (TextWriter writer = new StreamWriter(stream))
{
XmlSerializer serializer = new XmlSerializer(typeof(Product));
serializer.Serialize(writer, product);
}
}