Click here to Skip to main content
Click here to Skip to main content

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

, 24 Jun 2009
Rate this:
Please Sign up or sign in to vote.
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
[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)

About the Author

farzaneh ansari
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

 
GeneralMy Vote of 5 PinmemberAshish Ramteke29-May-13 1:12 
GeneralRe: My Vote of 5 Pinmemberfarzaneh ansari29-May-13 1:52 
GeneralMy vote of 5 PinmemberVasistan Shakkaravarthi11-Dec-12 2:15 
GeneralMy vote of 5 Pinmemberrobbiegis31-Oct-12 18:59 
GeneralMy vote of 5 PinmemberB.Farivar20-Oct-12 21:07 
BugExchange PinmemberDrazen Pupovac27-Dec-11 1:05 
GeneralMy vote of 3 PinmemberJamil Hallal11-May-11 3:28 
GeneralSome additions Pinmemberdimzon20-Jul-09 5:47 
GeneralVery Good Article. Pinmemberjesusfuentes16-Jul-09 9:50 
GeneralMy vote for this article is 3 Pinmemberramuknavap30-Jun-09 14:25 
GeneralRe: My vote for this article is 3 PinmemberDennis Dykstra3-Jul-09 5:02 
GeneralRe: My vote for this article is 3 Pinmemberfarzaneh ansary4-Jul-09 18:47 
GeneralRe: My vote for this article is 3 Pinmemberfarzaneh ansary4-Jul-09 18:41 
GeneralRe: My vote for this article is 3 PinmemberRTS@Orix6-Jul-09 4:02 
GeneralNice to see an Iranian on-line ... Pinmemberxlg30-Jun-09 3:16 
GeneralRe: Nice to see an Iranian on-line ... Pinmemberfarzaneh ansary4-Jul-09 18:44 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 24 Jun 2009
Article Copyright 2009 by farzaneh ansari
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid