Click here to Skip to main content
6,822,613 members and growing! (15,611 online)
Email Password   helpLost your password?
License: The Code Project Open License (CPOL)

Serializing and Deserializing Objects…to and from…XML

By Steve Wellens

Over on the Asp.Net forums I recently had the opportunity* to help a few lost souls by showing them how to serialize objects to XML and deserialize the XML back into objects. Since the question has come up more than once, I decided to BLOG it so I could refer similar questions in the future to this 
C#, XML, Windows, .NET, DBA, Dev
Revision:7 (See All)
Posted:2 Jul 2009
Updated:6 Jan 2010
Views:4,591
Bookmarked:13 times
Technical Blog
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
3 votes for this technical blog.
Popularity: 1.75 Rating: 3.67 out of 5
1 vote, 33.3%
1

2

3

4
2 votes, 66.7%
5

Over on the Asp.Net forums I recently had the opportunity* to help a few lost souls by showing them how to serialize objects to XML and deserialize the XML back into objects. Since the question has come up more than once, I decided to BLOG it so I could refer similar questions in the future to this post.

*I use the word opportunity because by helping others I am forced to think hard about the technology and to think even harder about how to communicate the technology. It makes me better at what I do. All right then, enough after-school-special-feel-good-about-yourself-I'm-ok-you're-ok fluffy nonsense… on with the code:

Here is a simple class I'm going to work with. It has both properties and fields:

public class MyClass
{
    // old school property
    private int _Age;  
    public int Age  
    {
        get { return _Age; }
        set { _Age = value; }
    }

    // new school property
    public bool Citizen { get; set; }

    // there's nothing wrong with using fields
    public string Name;  
}

Here are the two functions to Serialize and Deserialize an object:

 
/// ---- SerializeAnObject -----------------------------
/// <summary>
/// Serializes an object to an XML string
/// </summary>
/// <param name="AnObject">The Object to serialize</param>
/// <returns>XML string</returns>
 
public static string SerializeAnObject(object AnObject)
{
    XmlSerializer Xml_Serializer = new XmlSerializer(AnObject.GetType());
    StringWriter Writer = new StringWriter();      

    Xml_Serializer.Serialize(Writer, AnObject);
    return Writer.ToString();
} 

/// ---- DeSerializeAnObject ------------------------------
/// <summary>
/// DeSerialize an object
/// </summary>
/// <param name="XmlOfAnObject">The XML string</param>
/// <param name="ObjectType">The type of object</param>
/// <returns>A deserialized object...must be cast to correct type</returns>
 
public static Object DeSerializeAnObject(string XmlOfAnObject, Type ObjectType)
{       
    StringReader StrReader = new StringReader(XmlOfAnObject);
    XmlSerializer Xml_Serializer = new XmlSerializer(ObjectType);
    XmlTextReader XmlReader = new XmlTextReader(StrReader);
    try
    {
        Object AnObject = Xml_Serializer.Deserialize(XmlReader);
        return AnObject;
    }
    finally
    {
        XmlReader.Close();
        StrReader.Close();
    }
}

Here is some sample code showing how to use the functions.

Note: I keep these functions (and other functions) in a class I call MiscUtilities. You will have to modify the code…depending on where you place the functions.

protected void Button1_Click(object sender, EventArgs e)
{
    // create and initialize an object
    MyClass Test = new MyClass();
 
    Test.Age = 18;
    Test.Name = "Rocky Balboa";
    Test.Citizen = true;
 
    //  Serialize it
    String XML;
 
    XML = MiscUtilities.SerializeAnObject(Test);
 
    // Deserialize it
    MyClass Test2;
 
    Test2 = MiscUtilities.DeSerializeAnObject(XML, typeof(MyClass)) as MyClass;
 
    // TODO:  Get a cup of coffee and bask in the glory of rock solid code.
}

Here is what the XML string looks like (after formatting):

<?xml version="1.0"?>
<MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>Rocky Balboa</Name>
  <Age>18</Age>
  <Citizen>true</Citizen>
</MyClass>                

There are limitations: XmlSerializer does not serialize private fields, methods, indexers or read-only fields.

Once you have the XML string, you can email it, store it in a database, save it to disk, or…print a copy of it and have your mom tape it to the refrigerator next to the turkey picture you made in the second grade by tracing around your hand with a Crayola crayon.

I hope someone finds this useful.

License

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

About the Author

Steve Wellens


Member
I am an independent contractor/consultant working in the Twin Cities area in Minnesota. I work in .Net, Asp.Net, C#, C++, XML, SQL, Windows Forms, HTML, CSS, etc., etc., etc.
Company: EndWell Software, Inc.
Location: United States United States

Other popular XML articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 3 of 3 (Total in Forum: 3) (Refresh)FirstPrevNext
GeneralMy vote of 1 PinmemberRussell Garner11:13 2 Jul '09  
GeneralRe: My vote of 1 PinassociateSteve Wellens11:21 2 Jul '09  
GeneralHmm PinmemberJefis11:07 2 Jul '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

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

PermaLink | Privacy | Terms of Use
Last Updated: 6 Jan 2010
Editor:
Copyright 2009 by Steve Wellens
Everything else Copyright © CodeProject, 1999-2010
Web21 | Advertise on the Code Project