Pages

Thursday, March 27, 2008

.NET serializing object to XML and then converting to String

Code snippet:

What I wanted: I have a collection (dictionary) of custom objects and I wanted all of them to be logged using my logging method.

XmlSerializer xs = new XmlSerializer(typeof(CustomObject));

//enumerate through each key value pair and log them.
foreach(CustomObject csObj in this._CustomCollection)
{
//XML output to memory stream
MemoryStream ms = new MemoryStream();

//Serialize each node of the paragraph test
xs.Serialize(ms, csObj );

//Get the string from the memory stream buffer
UTF8Encoding encoding = new UTF8Encoding();
String myString = encoding.GetString(ms.GetBuffer());
myString .TrimStart();

//Call your logging mechanism
MyLog.WriteXml(myString);
}

2 comments:

Celular said...

Hello. This post is likeable, and your blog is very interesting, congratulations :-). I will add in my blogroll =). If possible gives a last there on my blog, it is about the Celular, I hope you enjoy. The address is http://telefone-celular-brasil.blogspot.com. A hug.

Global Handler said...

Thanks will add your's in mine.
I have to read using the translator as I do not understand portugese/brasil