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:
(ignore the type name being upper case in my example, it's caused by the code highlighter)
MyTargetType deserialized = Deserialize(xmlReader, "startnode");
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
This method looks very familiar :-)
ReplyDelete