Appendix W Serialization
This appendix summarizes useful serialization topics and techniques.
XML Serialization
To serialize and deserialize objects in XML format, you use the XmlSerializer
class’s Serialize
and Deserialize
methods. The methods work only for classes that have a parameterless constructor, either the default constructor or one that you created. They also work only for public properties and fields. All other properties and fields are ignored.
To serialize an object, follow these steps.
- Create an
XmlSerializer
, passing its constructor the object’s type. - Create a
TextWriter
to hold the serialization. - Call the serializer’s
Serialize
method, passing it theTextWriter
and the object to serialize.
The following code shows how a program might serialize a Customer
object.
// Create a serializer that works with the Customer class.
XmlSerializer serializer = new XmlSerializer(typeof(Customer));
// Create a TextWriter to hold the serialization.
string serialization;
using (TextWriter writer = new StringWriter())
{
// Serialize the Customer.
serializer.Serialize(writer, customer);
serialization = writer.ToString();
}
// Display the serialization.
serializationTextBox.Text = serialization;
To deserialize a serialization, follow these steps.
- Create an
XmlSerializer
, passing its constructor the object’s type. - Create a
TextReader
from which to read the serialization. - Call the serializer’s
Deserialize
method, passing it theTextReader
. Cast the result into the object’s type.
Get C# 5.0 Programmer's Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.