Skip to content

C# generics and XML deserializing

I’ve been playing with generics more, trying to ease the slog of C# development. The .NET framework allows you to do damn near everything, but its so freaking verbose. Almost anything I want to do with framework classes ends up taking 4-5 nearly identical lines, so I end up writing a lot of little wrapper functions to make one-liners.

The task I had at hand this time was to take a string of XML and deserialize is back into a C# object. I generated the C# object off of an .xsd file using xsd.exe (more info), so it has the spaghetti of attributes needed for the XmlSerializer.

public static T DeserializeFromXml<T>(string xml){
	T result;
	XmlSerializer ser = new XmlSerializer(typeof(T));
	using(TextReader tr = new StringReader(xml)) {
		result = (T) ser.Deserialize(tr);				
	return result;

With that utility function, now I can just:

MyClass obj = Utils.DeserializeFromXml<MyClass>(xml);

Working with these libraries, I always end up pondering why Microsoft didn’t think to include shortcuts like this.


  1. Pasx wrote:

    Thank you for this very useful piece of code.
    You can post this opposite function which serializes to a file any serializable object.

    public static bool SerializeToFile(string fileName, T obj)
    TextWriter tw = null;
    XmlSerializer xs = new XmlSerializer(typeof(T));
    tw = new StreamWriter(fileName);
    xs.Serialize(tw, obj);
    return true;
    return false;
    if (tw != null) tw.Close();

    Monday, September 29, 2008 at 4:07 pm | Permalink
  2. Nile wrote:

    Thanks for the good technique

    Thursday, October 16, 2008 at 4:50 am | Permalink