XML Serialization

So far, you have constructed the XML representing the Customer objects by hand. As XML is becoming popular, especially with the acceptance of web services as a central component of the SOA, it is increasingly common to serialize objects into XML, transmit them across process and application boundaries, and deserialize them back into conventional objects.

Tip

For more information about SOA, see Programming WCF Services by Juval Löwy (O'Reilly).

It is therefore natural for the .NET Framework to provide a built-in serialization mechanism, as a part of the Windows Communication Foundation (WCF), to reduce the coding efforts by application developers. The System.Xml.Serialization namespace defines the classes and utilities that implement methods required for serializing and deserializing objects. Example 14-5 illustrates this.

Example 14-5. Simple XML serialization and deserialization

using System; using System.IO; using System.Xml.Serialization; namespace Programming_CSharp { // Simple customer class public class Customer { public string FirstName { get; set; } public string LastName { get; set; } public string EmailAddress { get; set; } // Overrides the Object.ToString( ) to provide a // string representation of the object properties. public override string ToString( ) { return string.Format("{0} {1}\nEmail: {2}", FirstName, LastName, EmailAddress); } } // Main program public class Tester { static void Main( ) { Customer c1 = new Customer { FirstName = "Orlando", LastName ...

Get Programming C# 3.0, 5th Edition 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.