According to MSDN, "XML serialization converts
(serializes) the public fields and properties of an object or the parameters
and returns values of methods, into an XML stream that conforms to a specific
XML Schema definition language (XSD) document. XML serialization results in
strongly typed classes with public properties and fields that are converted to
a serial format (in this case, XML) for storage or transport. Because XML is an
open standard, the XML stream can be processed by any application, as needed,
regardless of platform." Implementing XML Serialization in .Net is quite
simple. The basic class that we need to use is the XmlSerializer for both
serialization and de-serialization. The Web Services use the SOAP protocol for
communication and the return types and the parameters are all serialized using
the XmlSerializer class. XML Serialization is however, much slower compared to
Binary serialization. We can set a property as an XML attribute as shown in
the code listing below.
Listing 6:
[XmlAttribute("empName")]
public string EmpName
{
get
{
return empName;
}
set
{
empName = value;
}
}
The following code listing shows how we can implement XML
serialization.
Listing 7:
public void XMLSerialize(Employee emp, String filename)
{
XmlSerializer serializer = null;
FileStream stream = null;
try
{
serializer = new XmlSerializer(typeof(Employee));
stream = new FileStream(filename, FileMode.Create, FileAccess.Write);
serializer.Serialize(stream, emp);
}
finally
{
if (stream != null)
stream.Close();
}
}
The following code listing shows how we can implement XML de-serialization.
Listing 8:
public static Employee XMLDeserialize(String filename)
{
XmlSerializer serializer = null;
FileStream stream = null;
Employee emp = new Employee();
try
{
serializer = new XmlSerializer(typeof(Employee));
stream = new FileStream(filename, FileMode.Open);
emp = (Employee)serializer.Deserialize(stream);
}
finally
{
if (stream != null)
stream.Close();
}
return emp;
}