A few classes cannot be serialized to XML because they do not support ISerializable. The most notable being the Dictionary class. However, if it can't serialize, it will just throw an exception about it.
Code:using System.Xml; using System.Xml.Serialization; using System.IO; public string Serialize<T>(T entity) { StringBuilder outputXml = new StringBuilder(); if (typeof(T).IsSerializable) { XmlSerializer ser = new XmlSerializer(typeof(T)); using (TextWriter stream = new StringWriter(outputXml)) { ser.Serialize(stream, entity); } return outputXml.ToString(); } return null; } public T Deserialize<T>(string xml) { T entity; if (typeof(T).IsSerializable) { XmlSerializer ser = new XmlSerializer(typeof(T)); using (TextReader stream = new StringReader(xml)) { entity = (T)ser.Deserialize(stream); } return entity; } return null; }




Reply With Quote