Archive for the ‘persist’ tag
Persist .NET objects to XML
Here’s two extensions I use to easily persist objects to XML string in C#. Although it looks like it, it does not seem to require that the class of the object is decorated with the DataContract attribute, it just works.
public static string ToXml(this object o) { StringWriter sw = new StringWriter(); XmlWriter xw = XmlWriter.Create(sw); DataContractSerializer dcs = new DataContractSerializer(o.GetType()); dcs.WriteObject(xw, o); xw.Close(); return sw.ToString(); } public static T FromXmlTo(this string s) where T : class { DataContractSerializer dcs = new DataContractSerializer(typeof(T)); StringReader sr = new StringReader(s); XmlReader xtr = XmlReader.Create(sr); return dcs.ReadObject(xtr) as T; }
Let me here how it works out for you guys..