Geeks With Blogs
Gaurav Taneja Great dreams... never even get out of the box. It takes an uncommon amount of guts to put your dreams on the line, to hold them up and say, "How good or how bad am I?" That's where courage comes in.

Serialize (convert an object instance to an XML document):

 

// Assuming obj is an instance of an object

XmlSerializer ser = new XmlSerializer(obj.GetType());

System.Text.StringBuilder sb = new System.Text.StringBuilder();

System.IO.StringWriter writer = new System.IO.StringWriter(sb);

ser.Serialize(writer, obj);

XmlDocument doc = new XmlDocument();

doc.LoadXml(sb.ToString());

 

Deserialize (convert an XML document into an object instance):

 

//Assuming doc is an XML document containing a serialized object and objType is a System.Type set to the type of the object.

XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);

XmlSerializer ser = new XmlSerializer(objType);

object obj = ser.Deserialize(reader);

// Then you just need to cast obj into whatever type it is eg:

MyClass myObj = (MyClass)obj;

Posted on Saturday, September 30, 2006 4:27 AM | Back to top


Comments on this post: Serialize & Deserialize + C#

# re: Serialize & Deserialize
Requesting Gravatar...
Hi,

You could also use generics in .NET 2.0 to write a helper to do this:

http://blogs.conchango.com/howardvanrooijen/archive/2006/05/21/GenericsAndSerialization.aspx
Left by Howard van Rooijen on Oct 03, 2006 10:56 AM

Your comment:
 (will show your gravatar)


Copyright © Gaurav Taneja | Powered by: GeeksWithBlogs.net