Thursday, December 2, 2010

C#: Deserialize Xml (string) to an Object

A while back I posted an entry to be able to simply Serialize an object into Xml. Now it is time to do the reverse. Not sure if this will work for all types of complex objects but I have not received any errors so far. Of course, it would be a good idea for the calling program to cast the returned object appropriately.

public static object DeserializeXml(string xml, System.Type objectType)
{
byte[] byteArray = Encoding.ASCII.GetBytes(xml);
MemoryStream memoryStream = new MemoryStream(byteArray);
XmlSerializer xmlSerializer = new XmlSerializer(objectType);
Object obj = xmlSerializer.Deserialize(memoryStream);
memoryStream.Close();
return obj;
}

No comments:

Post a Comment

Please use your common sense before making a comment, and I truly appreciate your constructive criticisms.