I have a bunch of objects that were serialized to XML. Now I want to deserialize them, but since I don’t know what the type is for a given XML string, I can’t figure out how to do it. Here is the code I am using when I know what type (Task in this case) the objects are:
public static Task DeserializeFromXML(string value)
{
Task task = new Task();
StringReader reader = new StringReader(value);
XmlSerializer serializer = new XmlSerializer(task.GetType());
XmlReader xmlReader = new XmlTextReader(reader);
task = (Task)serializer.Deserialize(xmlReader);
return task;
}
I’m confused since XmlSerializer needs a type passed to the constructor and the Deserialize method eventually needs to be cast from Object to whatever I just deserialized, but I don’t know what that type is at this point.
The XML serializer does not include information about the kind of objects that are serialized out. With straight XML, you don’t have a way around this. The object type is not included in the serialization.
Some other serializers in .NET (notably the NetDataContractSerializer) do include enough information to reconstruct specific object types without knowing them ahead of time.