CHAPTER 20 FILE I/O AND OBJECT SERIALIZATION
Figure 20-6. JamesBondCar serialized using a SoapFormatter
Serializing Objects Using the XmlSerializer
In addition to the SOAP and binary formatters, the System.Xml.dll assembly provides a third formatter,
System.Xml.Serialization.XmlSerializer. You can use this formatter to persist the public state of a
given object as pure XML, as opposed to XML data wrapped within a SOAP message. Working with this
type is a bit different from working with the SoapFormatter or BinaryFormatter type. Consider the
following code, which assumes you have imported the System.Xml.Serialization namespace:
static void SaveAsXmlFormat(object objGraph, string fileName)
{
// Save object to a file named CarData.xml in XML format.
XmlSerializer xmlFormat = new XmlSerializer(typeof(JamesBondCar));
using(Stream fStream = new FileStream(fileName,
FileMode.Create, FileAccess.Write, FileShare.None))
{
xmlFormat.Serialize(fStream, objGraph);
}
Console.WriteLine("=> Saved car in XML format!");
}
The key difference is that the XmlSerializer type requires you to specify type information that
represents the class you want to serialize. If you were to look within the newly generated XML file
(assuming you call this new method from within Main()), you would find the XML data shown here:
truefalse
790