XML serialization enables us to transform an instance of some class to XML and vice versa. Developers often need to perform XML serialization.
Listing 8.12 presents an example of XML serialization. In this example, there is a simple class that needs to be serialized: CellPhone. The first step is to create an instance of the class XmlSerializer and initialize is with the type XMLSerializationSample.CellPhone. Next, the CellPhone class is instantiated and the properties set to the desired values. Finally, the Serialize method is invoked and the CellPhone is serialized.
The result of the example's run is shown in Listing 8.13.
The following lines show us how to deserialize XML by using Deserialize() method:
XmlSerializer serializer = new XmlSerializer(Type.GetType("XMLSerializationSample.CellPhone")); CellPhone anotherCellPhone = (CellPhone) serializer.Deserialize(new XmlTextReader("cellphone.xml")); Console.WriteLine(anotherCellPhone.Description);
In the preceding section, you learned how to serialize an object by using XmlSerialization. This section shows you how to customize this class. For example, suppose that you need to represent a public property of a class not as an XML element, but as an XML attribute. However, the standard serialization process converts public properties into XML elements only. Therefore, you will need to customize the serialization process to accomplish your goal.
There are several predefined metadata attributes in .NET that enable us to customize serialization. They control how classes are mapped to XML and contain auxiliary information for Serialize() and Deserialize() methods of the XmlSerializer class. Each attribute customizes how XmlSerializer maps a class, field, or property to an XML document. The attributes can also declare types that are not explicitly referenced in a source file.
Now let's tune the source code defined in Listing 8.12 by adding serialization attributes to the class and properties definitions (Listing 8.14).
As you can see, the definition of the CellPhone class has changed in the following way:
The XmlRoot attribute was added ([XmlRoot("cell-phone")]) before the class declaration; now the root element of XML will be cell-phone.
The XmlAttribute attributes were added before the Name and Year properties ([XmlAttribute("name")], [XmlAttribute("year")]). They will be defined in the XML as attributes of the cell-phone node.
The Description property has been declared with the attribute XmlElement ([XmlElement("description")]). In the resulting XML document, the description node will be presented inside the cell-phone node.
Listing 8.15 shows the result of running the example described in Listing 8.14.
18.188.154.252