Tim Huffam

Dotting the I and crossing the T of I.T.

  Home  |   Contact  |   Syndication    |   Login
  129 Posts | 0 Stories | 874 Comments | 677 Trackbacks

News

Archives

Post Categories

Interesting Blogs/Links

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;

HTH
Tim

posted on Thursday, February 09, 2006 2:59 PM

Feedback

# re: Serialization: How to serialize and deserialize using C# .NET 6/15/2006 10:17 PM Lost but now found
Just what I was looking for!! Yippie!

# re: Serialization: How to serialize and deserialize using C# .NET 1/9/2008 11:40 AM Ridge Wong(China)
easy but power! many tks~

# re: Serialization: How to serialize and deserialize using C# .NET 1/31/2008 4:13 AM mstern
Very fine stuff!

# re: Serialization: How to serialize and deserialize using C# .NET 4/2/2008 7:52 PM ss
Hi,

whether this code is working. When i put breakpoint in the following line, i could see that the value is none.

XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);

Why is it so?

# re: Serialization: How to serialize and deserialize using C# .NET 4/12/2008 1:25 AM Anonymous
Works great! Thank you so much. It took me forever to find an example on how to do this!

# re: Serialization: How to serialize and deserialize using C# .NET 6/17/2008 4:23 AM pae
I implemented deserialization from an xml i read from disk but the deserialized object does not have the info the xml had, only the properties. Why?

# re: Serialization: How to serialize and deserialize using C# .NET 6/17/2008 10:14 AM pae
Is ok, was a nameSpaces issue, now is working fine, nice post, short, simple and very userful!!!

# re: Serialization: How to serialize and deserialize using C# .NET 7/15/2008 3:49 AM xlthim
Every sample I read is a great example of reading 1 object in with a few attributes. I need to read multiple objects in with multiple attributes... Like a collection of books, each with a title, isbn, author, price... How do I create a book object, add the attributes for that book, save it to a List<>, then read in the next book? tks xlthim

Post Feedback

Title:
Name:
Email: (never displayed)
Url:
Comments: 
Please add 8 and 5 and type the answer here: