Monday, July 27, 2009

Generic XML deserializer method

For one of my projects i needed to deserialize several XML files to objects of different data types.
Therefore i wrote this generic deserialization method:

public static T Deserialize(XmlReader xmlReader, string rootElement)
{
T result;

XmlRootAttribute root = new XmlRootAttribute(rootElement);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T), root);
result = (T)xmlSerializer.Deserialize(xmlReader);

return result;
}

To use it, you first load your XML file into an XmlReader object and call the method like this:

MyTargetType deserialized = Deserialize(xmlReader, "startnode");
(ignore the type name being upper case in my example, it's caused by the code highlighter)

I will post some more later about how you can let your application use its configuration to decide what data type specific XML files should be deserialized to.
This can be very usefull when you have an application that deserializes multiple XML feeds and you want the list of feeds to be configurable outside of the code.

/Ruud

1 comment: