Click here to Skip to main content
15,885,954 members
Articles / Web Development / ASP.NET

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

Rate me:
Please Sign up or sign in to vote.
4.86/5 (20 votes)
24 Jun 2009CPOL3 min read 153K   4.2K   44   16
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 attribute
  • XmlElementAttribute—The field or property will be serialized as an XML element
  • XmlIgnoreAttribute—The field or property will be ignored when serializing
  • XmlRootAttribute—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() or Deserialize() method of the XmlSerializer class, passing in the object to be serialized or deserialized
C#
[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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer PascalSystem,is located in Iran-Isfahan
Iran (Islamic Republic of) Iran (Islamic Republic of)
I was graduated from Esfahan unversity(BS Applied Mathematics)
Master of Computer Science at Saarland University

Comments and Discussions

 
QuestionHow To Deserialize an xml without knowing the type in Rest Service? Pin
Member 110998604-Dec-14 21:54
Member 110998604-Dec-14 21:54 
GeneralMy vote of 5 Pin
Vasistan Shakkaravarthi11-Dec-12 2:15
Vasistan Shakkaravarthi11-Dec-12 2:15 
GeneralMy vote of 5 Pin
robbiegis31-Oct-12 18:59
robbiegis31-Oct-12 18:59 
GeneralMy vote of 5 Pin
B.Farivar20-Oct-12 21:07
B.Farivar20-Oct-12 21:07 
BugExchange Pin
Drazen Pupovac27-Dec-11 1:05
Drazen Pupovac27-Dec-11 1:05 
GeneralMy vote of 3 Pin
Jamil Hallal11-May-11 3:28
professionalJamil Hallal11-May-11 3:28 
GeneralSome additions Pin
dimzon20-Jul-09 5:47
dimzon20-Jul-09 5:47 
GeneralVery Good Article. Pin
jesusfuentes16-Jul-09 9:50
jesusfuentes16-Jul-09 9:50 
GeneralMy vote for this article is 3 Pin
ramuknavap30-Jun-09 14:25
ramuknavap30-Jun-09 14:25 
GeneralRe: My vote for this article is 3 Pin
Dennis Dykstra3-Jul-09 5:02
Dennis Dykstra3-Jul-09 5:02 
GeneralRe: My vote for this article is 3 Pin
farzaneh ansari4-Jul-09 18:47
farzaneh ansari4-Jul-09 18:47 
GeneralRe: My vote for this article is 3 Pin
farzaneh ansari4-Jul-09 18:41
farzaneh ansari4-Jul-09 18:41 
GeneralRe: My vote for this article is 3 Pin
RTS@WORK6-Jul-09 4:02
RTS@WORK6-Jul-09 4:02 
I Agree that this rating is unfounded. I've worked in many shops that are on 2.0 and have no plans of moving.
GeneralNice to see an Iranian on-line ... Pin
xlg30-Jun-09 3:16
xlg30-Jun-09 3:16 
GeneralRe: Nice to see an Iranian on-line ... Pin
farzaneh ansari4-Jul-09 18:44
farzaneh ansari4-Jul-09 18:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.