Deserialize object xml string into an object instance

By Miguel Santos

Given xml string that contains a deserialized object. This code will convert this string into the desired object. (Keep in mind that object has to be serializable)

public static T RestoreXmlStringToObj<T>(string xml)
{
            var Encoding = new System.Text.UnicodeEncoding();
            var xmlStream = new MemoryStream(Encoding.GetBytes(xml));
            
            using(MemoryStream xmlStream = new MemoryStream(Encoding.GetBytes(xml))
            {
                var xmlSerializer = new XmlSerializer(typeof(T));
                return (T)xmlSerializer.Deserialize(xmlStream);
             }
  }

Deserialize object xml string into an object instance  (1578 Views)