To achieve this, we can use the XmlWriter class provided by the following namespaces: "System.Xml", "System.Xml.Serialization" and "System.IO". Here is a custom code snippet, where the first parameter is the string and return type of method is generic T.
- public static T Deserialize<T>(string xml)
- {
- if (String.IsNullOrEmpty(xml)) throw new NotSupportedException("Empty string!!");
-
- try
- {
- var xmlserializer = new XmlSerializer(typeof(T));
- var stringReader = new StringReader(xml);
- using (var reader = XmlReader.Create(stringReader))
- {
- return (T)xmlserializer.Deserialize(reader);
- }
- }
- catch (Exception e)
- {
- throw new Exception(e.Message);
- }
- }