Serialize and Deserialize Objects as XML using Generic Types in C# 2.0






4.86/5 (18 votes)
A simple scenario to demonstrate how an instance of an object is created and serialized into a file stream and stored into database using the Serialize method
Introduction
This example uses a simple scenario to demonstrate how an instance of an object is created and serialized into a file stream and stored into database using the Serialize
method.The XML stream is saved to a file, and the same file is then read back and reconstructed into a copy of the original object using the Deserialize
method.
Serialization is the process of converting the state of an object into a form that can be persisted or transported. The complement of serialization is deserialization, which converts a stream into an object. Together, these processes allow data to be easily stored and transferred.
There are two serializing technologies provided by the Microsoft .NET Framework. Binary serialization preserves type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example, you can share an object between different applications by serializing it to the Clipboard. You can serialize an object to a stream, to a disk, to memory, over the network, and so forth. Remoting uses serialization to pass objects "by value" from one computer or application domain to another.
XML & SOAP serialization serializes only public
properties and fields and does not preserve type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data. Because XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is likewise an open standard, which makes it an attractive choice.
XML serialization converts (serializes) the public
fields and properties of an object, or the parameters and return 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.To serialize or deserialize objects, use the System.Xml.Serialization.XmlSerializer
class.
Controlling XML Serialization with Attributes
Attributes can be used to control serialization of an object performed by the XmlSerializer
. Some of the attributes available are as follows:
XmlAttributeAttribute
—The member will be serialized as an XML attributeXmlElementAttribute
—The field or property will be serialized as an XML elementXmlIgnoreAttribute
—The field or property will be ignored when serializingXmlRootAttribute
—Represents the XML document's root element name, only applies to a class
To serialize and deserialize a generic class, you just need to follow two steps:
- Create an instance of the
XmlSerializer
class and pass the type of the generic type to be serialized as an argument - Invoke the
Serialize()
orDeserialize()
method of theXmlSerializer
class, passing in the object to be serialized or deserialized
[XmlRoot("PersonInfoXml")]
public class Person
{
[XmlElement("Name")]
public Identifier PersonIdentify
{
get
{
if (mIdentify == null) mIdentify = new Identifier();
return mIdentify;
}
set { mIdentify = value; }
}
[XmlElement("Address")]
public Address PersonAddress
{
get
{
if (mAddress == null)
mAddress = new Address();
return mAddress;
}
set { mAddress = value; }
}
[XmlElement("Education")]
public Education PersonEducation
{
get
{
if (mEducation == null)
mEducation = new Education();
return mEducation;
}
set { mEducation = value; }
}
private List<string> mSkills;
[System.Xml.Serialization.XmlArrayItemAttribute(ElementName = "Skill",
IsNullable = false)]
public List<string> Skills
{
get { return mSkills; }
set { mSkills = value; }
}
public class Identifier
{
#region Constructor
public Identifier()
{
}
public Identifier(string firstname,string lastname,string sex)
{
mFirstName = firstname;
mLastName = lastname;
mSex = sex;
}
#endregion
#region Properties
private String mFirstName;
private String mLastName;
private String mSex;
public String FirstName
{
get{return mFirstName;}
set{mFirstName = value;}
}
public String LastName
{
get{return mLastName;}
set{mLastName = value;}
}
public String Sex
{
get { return mSex; }
set { mSex = value; }
}
#endregion
}
public class Address
{
#region Constructor
public Address()
{
}
public Address(string address, string city, string state, string country,
string phone)
{
mAddressS = address;
mCity = city;
mState = state;
mCountry = country;
mPhone = phone;
}
#endregion
#region Properties
private String mAddressS;
private String mCountry;
private String mCity;
private String mState;
private String mPhone;
public String AddressS
{
get { return mAddressS; }
set { mAddressS = value; }
}
public String Country
{
get{return mCountry;}
set{mCountry = value;}
}
public String City
{
get{return mCity;}
set{mCity = value;}
}
public String State
{
get { return mState; }
set { mState = value; }
}
public String Phone
{
get { return mPhone; }
set { mPhone = value; }
}
#endregion
}
public class Education
{
#region Constructor
public Education()
{
}
public Education(string bachelorDegree,string masterDegree)
{
mBachelor = bachelorDegree;
mMaster = masterDegree;
}
#endregion
#region Properties
private String mBachelor;
private String mMaster;
public String Bachelor
{
get { return mBachelor; }
set { mBachelor = value; }
}
public String Master
{
get { return mMaster; }
set { mMaster = value; }
}
#endregion
}}
public static void SerializeToXml<T>(T obj, string fileName)
{
XmlSerializer ser = new XmlSerializer(typeof(T));
ser.Serialize(fileStream, obj);
fileStream.Close();
FileStream fileStream = new FileStream(fileName, FileMode.Create);
}
public static T DeserializeFromXml<T>(string xml)
{
T result;
XmlSerializer ser = new XmlSerializer(typeof(T));
using (TextReader tr = new StringReader(xml))
{
result = (T)ser.Deserialize(tr);
}
return result;
This example uses a simple scenario to demonstrate how an instance of an object is created and serialized into a file stream and stored into database using the Serialize
method. The XML stream is saved to a file, and the same file is then read back and reconstructed into a copy of the original object using the Deserialize
method.
In this example, a class named Person
is serialized and then deserialized. A second class named Identifier
is also included because the public
field named ShipTo
must be set to an FirstName&LastNAme &Sex
.Similarly, an Address
and Education
class is included because the public
field objects of Address
or Education
must be set to the OrderedItems
field. Finally, a Generics List Skills serializes and deserializes the classes.
History
- 24th June, 2009: Initial post