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:
-
Create a stream, TextWriter, or XmlWriter object to hold the serialized output.
-
Create an XmlSerializer object (in the System.Xml.Serialization namespace) by passing it the type of object you plan to serialize.
-
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();

sraddhan shahPosted Jul 16, 2007, 2:58 AM
can we serialize more than one objects in the same xml document? If yes then how to deserialize them?