Geeks With Blogs
Paul's development blog Tidbits from Smart Client, Windows Forms, C#, .NET 2.0, XML, and related toys...

I've been using Object<>Xml serialization in .NET based on this post for a while. I decided to enhance it a tad bit with some generics, so I could use it more broadly. Here's what I came up with:

using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Serialization;

/// <summary>
///
To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
///
</summary>
///
<param name="characters">Unicode Byte Array to be converted to String
</param>
///
<returns>String converted from Unicode Byte Array
</returns>
private static string UTF8ByteArrayToString(byte[] characters)
{
   UTF8Encoding encoding = new UTF8Encoding();
   string constructedString = encoding.GetString(characters);
   return (constructedString);
}

/// <summary>
///
Converts the String to UTF8 Byte array and is used in De serialization
///
</summary>
///
<param name="pXmlString"></param>
///
<returns></returns>
private static Byte[] StringToUTF8ByteArray(string pXmlString)
{
   UTF8Encoding encoding = new UTF8Encoding();
   byte[] byteArray = encoding.GetBytes(pXmlString);
   return byteArray;
}

/// <summary>
///
Serialize an object into an XML string
///
</summary>
///
<typeparam name="T"></typeparam>
///
<param name="obj"></param>
///
<returns></returns>
public static string SerializeObject<T>(T obj)
{
   try
   {
      string xmlString = null;
      MemoryStream memoryStream = new MemoryStream();
      XmlSerializer xs = new XmlSerializer(typeof(T));
      XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
      xs.Serialize(xmlTextWriter, obj);
      memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
      xmlString = UTF8ByteArrayToString(memoryStream.ToArray());      return xmlString;
   }
   catch
   {
      return string.Empty;
   }
}

/// <summary>
///
Reconstruct an object from an XML string
///
</summary>
///
<param name="xml"></param>
///
<returns></returns>
public static T DeserializeObject<T>(string xml)
{
   XmlSerializer xs = new XmlSerializer(typeof(T));
   MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(xml));
   XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
   return (T)xs.Deserialize(memoryStream);
}

Posted on Friday, July 20, 2007 8:35 AM | Back to top


Comments on this post: Serialize and deserialize objects as Xml using generic types in C# 2.0

# re: Serialize and deserialize objects as Xml using generic types in C# 2.0
Requesting Gravatar...
Great...thanks for help.
Left by Manohar on Jul 24, 2007 7:47 AM

# re: Serialize and deserialize objects as Xml using generic types in C# 2.0
Requesting Gravatar...
It seems that I wasn't the only one that edited that original codebase for C# 2.0! The only main difference between our code samples is that I implemented using constructs.

http://www.willasrari.com/blog/xml-serialization-with-c/000231.aspx
Left by Will Asrari on Aug 03, 2007 12:42 PM

# re: Serialize and deserialize objects as Xml using generic types in C# 2.0
Requesting Gravatar...
You should sourround the usage of the memorystream with a "using()".
Another suggestion: use a StreamReader instead of the encoding like so:

memoryStream.Seek(0, SeekOrigin.Begin);
using (StreamReader sr = new StreamReader(memoryStream)) {
return sr.ReadToEnd();
}
Left by TorstenR on Feb 07, 2008 10:06 PM

# re: Serialize and deserialize objects as Xml using generic types in C# 2.0
Requesting Gravatar...
very useful information!

thanks very much!
Left by kesulin on Feb 19, 2008 9:52 PM

# re: Serialize and deserialize objects as Xml using generic types in C# 2.0
Requesting Gravatar...
Very bad informations!
You have to try hard!
Left by Too bad on Mar 30, 2008 3:58 PM

# re: Serialize and deserialize objects as Xml using generic types in C# 2.0
Requesting Gravatar...
Great !
Thanx a lot,
messaoud
Left by Messaoud OUBECHOU on May 31, 2008 5:31 AM

# re: Serialize and deserialize objects as Xml using generic types in C# 2.0
Requesting Gravatar...
It's possible serialize a array, for example object[ ] ??
Left by Rafael on Aug 04, 2008 10:36 AM

# Serialize and deserialize objects as Xml using generic types in C# 2.0
Requesting Gravatar...
what is deserialization and how to see the output for deserialization afetr it is serialized.
plz provide me an example for deserialization followed by serialization.
Left by syam on Oct 04, 2008 4:09 AM

# re: Serialize and deserialize objects as Xml using generic types in C# 2.0
Requesting Gravatar...
It's possible serialize a array,
Left by lokritan on Nov 01, 2008 8:29 AM

# re: Serialize and deserialize objects as Xml using generic types in C# 2.0
Requesting Gravatar...
using your code i have converted my object to xml string

"return xmlString;"

Instead of returning an xml string i want to store this data as a xml file on the disk.

How can i do that do reply
Left by anandarajeshwaran on Dec 22, 2008 2:13 AM

# re: Serialize and deserialize objects as Xml using generic types in C# 2.0
Requesting Gravatar...
Your code is sloppy. You don't dispose of anything, nor do you do anything that isn't trivial.

Thanks for the blog, but it was useless.

What would be MORE useful would be taking an XML and generating an anonymous type. Talk about power, that would be amazing!
Left by Gary Smithson on Mar 14, 2009 4:44 AM

# re: Serialize and deserialize objects as Xml using generic types in C# 2.0
Requesting Gravatar...
@Gary thanks for your comment. this is pretty old code, but I've used a variant on several projects since I posted it. I'll see about updating it to tighten it up some.
Left by Paul Whitaker on Mar 14, 2009 5:11 AM

# re: Serialize and deserialize objects as Xml using generic types in C# 2.0
Requesting Gravatar...
thanks a lot !!

is possible change the date format in a xml ??

por example

class person
datetime fec;


in the output xml :
<person>
<fec>0001-01-01T00:00:00</fec>
</person>

i need change the date format
to any other like US or EN, or
dd-MM-yyyy

thanks
Left by Rodrigo on May 07, 2009 7:30 AM

# re: Serialize and deserialize objects as Xml using generic types in C# 2.0
Requesting Gravatar...
Hey Paul,

I found this useful and have converted it to VB.Net for your listeners to enjoy.

Cheers

Julian
Left by Julian Biddle on Aug 10, 2009 1:58 AM

# re: Serialize and deserialize objects as Xml using generic types in C# 2.0
Requesting Gravatar...
Humm... interesting,

of course we can resialze and array you can change the array to a list or some other genetic collectio and then do the seialization

Thanks
Left by web development company on Aug 21, 2009 11:59 AM

# re: Serialize and deserialize objects as Xml using generic types in C# 2.0
Requesting Gravatar...
From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! keep up the good work.
Left by macaroon on Aug 06, 2010 8:49 PM

# re: Serialize and deserialize objects as Xml using generic types in C# 2.0
Requesting Gravatar...
Lamentablemente .NET no serializa objetos que tengan referencias cruzadas o circulares, se debe agregar “Ingore” en tales casos, no me ha sido muy util dada la complejidad que tienen los objetos con los que trabajo, obligandome a repensar sobre el codigo que estoy utilizando.
Left by Daniel Molina Wegener on Aug 18, 2010 6:41 PM

# re: Serialize and deserialize objects as Xml using generic types in C# 2.0
Requesting Gravatar...
Good One..
Left by anirban on Jul 15, 2011 1:45 AM

# re: Serialize and deserialize objects as Xml using generic types in C# 2.0
Requesting Gravatar...
Perfect solution thank you
Left by Marc Roussel on Sep 14, 2011 9:30 AM

# re: Serialize and deserialize objects as Binary?
Requesting Gravatar...
Is it possible to do something similar with BINARY Serialization, instead of XML Serialization? Any one care to show working code please.
Left by neil on Apr 23, 2012 10:36 AM

# re: Serialize and deserialize objects as Xml using generic types in C# 2.0
Requesting Gravatar...
Either remove the try catch or do something useful in the catch. The way things are, there is no way to know things went wrong.
Left by Tarik on Jun 05, 2012 7:41 AM

# re: Serialize and deserialize objects as Xml using generic types in C# 2.0
Requesting Gravatar...
You are my hero. keep posting man...
Left by Ashish on Nov 29, 2012 11:40 PM

Your comment:
 (will show your gravatar)


Copyright © Paul Whitaker | Powered by: GeeksWithBlogs.net | Join free