XML De/serialization

Here’s a way to serialize and deserialize between a (serializable) type and XML (string).

Serialization from a type into XML (string) via a memory buffer:

public static string SerializeMyType(MyType obj)

{

      XmlSerializer xml = new XmlSerializer(typeof(MyType));

      MemoryStream ms = new MemoryStream();

 

      xml.Serialize(ms, obj);

 

      UTF8Encoding enc = new UTF8Encoding();

      ms.Seek(0, SeekOrigin.Begin);

 

 

      return enc.GetString(ms.ToArray());

 

}

 

 

Deserialization from an XML (string) into a type:

 

public static MyType DeserializeMyType(string xml)

{

      XmlSerializer xml = new XmlSerializer(typeof(MyType));

      TextReader tr = new StringReader(xml);

 

      return (MyType)xml.Deserialize(tr);

 

}

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s