Free mag vol1 | Page 846

CHAPTER 20  FILE I/O AND OBJECT SERIALIZATION [XmlText] The property or field will be serialized as XML text (i.e., the content between the start tag and the end tag of the root element). [XmlType] This attribute provides the name and namespace of the XML type. This simple example illustrates how the field data of JamesBondCar is currently persisted as XML: ... true false If you want to specify a custom XML namespace that qualifies the JamesBondCar and encodes the canFly and canSubmerge values as XML attributes, you can do so by modifying the C# definition of JamesBondCar, like so: [Serializable, XmlRoot(Namespace = "http://www.MyCompany.com")] public class JamesBondCar : Car { [XmlAttribute] public bool canFly; [XmlAttribute] public bool canSubmerge; } This yields the following XML document (note the opening element): ... Of course, you can use many other attributes to control how the XmlSerializer generates the resulting XML document. For full details, look up the System.Xml.Serialization namespace in the .NET Framework 4.5 SDK documentation. Serializing Collections of Objects Now that you have seen how to persist a single object to a stream, you’re ready to examine how to save a set of objects. As you might have noticed, the Serialize() method of the IFormatter interface does not provide a way to specify an arbitrary number of objects as input (only a single System.Object). On a related note, the return value of Deserialize() is, again, a single System.Object (the same basic limitation holds true for XmlSerializer). 792