XML Serialization in .NET Framework 2.0 : Part I

Introduction:

The .NET Framework includes several libraries for reading and writing XML files, including the System.Xml.Serialization namespace.

System.Xml.Serialization provides methods for converting objects, including those based on custom classes, to and from XML files. With XML serialization, you can write almost any object to a text file for later retrieval with only a few lines of code. Similarly, you can use XML serialization to transmit objects between computers through Web services-even if the remote computer is not using the .NET Framework.

How to Use XML to Serialize an Object:

At a high level, the steps for serializing an object are as follows:

  1. Create a stream, TextWriter, or XmlWriter object to hold the serialized output.
  2. Create an XmlSerializer object (in the System.Xml.Serialization namespace) by passing it the type of object you plan to serialize.
  3. Call the XmlSerializer.Serialize method to serialize the object and output the results to the stream.

Code:

// Create file to save the data to

FileStream fs = new FileStream("SerializedDate.XML", FileMode.Create);

// Create an XmlSerializer object to perform the serialization

XmlSerializer xs = new XmlSerializer(typeof(DateTime));

// Use the XmlSerializer object to serialize the data to the file

xs.Serialize(fs, System.DateTime.Now);

// Close the file

fs.Close();

How to Use XML to Deserialize an Object

To deserialize an object, follow these steps:

  1. Create a stream, TextReader, or XmlReader object to read the serialized input.
  2. Create an XmlSerializer object (in the System.Xml.Serialization namespace) by passing it the type of object you plan to deserialize.
  3. Call the XmlSerializer.Deserialize method to deserialize the object, and cast it to the correct type.

Code:

// Open file to read the data from

FileStream fs = new FileStream("SerializedDate.XML", FileMode.Open);

// Create an XmlSerializer object to perform the deserialization

XmlSerializer xs = new XmlSerializer(typeof(DateTime));

// Use the XmlSerializer object to deserialize the data from the file

DateTime previousTime = (DateTime)xs.Deserialize(fs);

// Close the file

fs.Close();

// Display the deserialized time

Console.WriteLine("Day: " + previousTime.DayOfWeek + ",

Time: " + previousTime.TimeOfDay.ToString());

Summary:

  1. XML serialization cannot be used to serialize private data or object graphs.
  2. To serialize an object, first create a stream, TextWriter, or XmlWriter. Then create an XmlSerializer object and call the XmlSerializer.Serialize method.
  3. To deserializean object, follow the same steps but call the XmlSerializer.Deserialize method.

Up Next
    Ebook Download
    View all
    Learn
    View all