Generic Functions for Object ↔ XML Serialization/Deserialization
public static string ToXml<T>(T source){ string result = null;
using (System.IO.StringWriter sw = new System.IO.StringWriter()) { using (System.Xml.XmlWriter writer = System.Xml.XmlTextWriter.Create(sw, null)) { System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T)); serializer.Serialize(writer, source); }
result = sw.ToString(); }
return result; }
public static T FromXml<T>(string xml){ T result = default(T);
if (string.IsNullOrEmpty(xml) == false) { using (System.IO.StringReader sr = new System.IO.StringReader(xml)) { System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T)); result = (T) serializer.Deserialize(sr); } }
return result;}
Leave a comment