Lars Holm Jensen's Code Blog

Just another WordPress codeblog on C#, Silverlight and all things .NET

Persist .NET objects to XML

without comments

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);
    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..

Written by larsholm

June 16th, 2011 at 9:06 pm

Posted in .NET

Tagged with , , , , ,