c# - Deserializing XML element to an Object when the element could be one of many possible elements -


within local framework messages transmitted in xml via pub/sub,i need able consume number of messages, however, messages received simple text , must deserialized objects created xsd tool.

the messages derived base messagetype element/object, if deserialize based on so:

xmlserializer serializer = new xmlserializer(typeof(messagetype)); xmlreader reader = xmlreader.create(new stringreader(rawmessage)); messagetype message = (messagetype)serializer.deserialize(reader);

i receive error says actual element type ("updateparameter" say) not expected.

at moment solution can think of use switch statement:

 xmlreader reader = xmlreader.create(new stringreader(upstring)); reader.movetocontent(); switch (reader.localname.tolower()) {    case "updateparameter":       serializer = new xmlserializer(typeof(updateparameter));       dostuff((updateparameter)serializer.deserialize(xml));       break;    case "updateparameterresponse":       serializer = new xmlserializer(typeof(updateparameterresponse));       dostuff((updateparameterresponse)serializer.deserialize(xml));       break;    case "updatestatusresponse":       serializer = new xmlserializer(typeof(updatestatusresponse));       dostuff((updatestatusresponse)serializer.deserialize(xml));       break; //...etc. repeat possible elements }

but i'd rather not if there elegent solution. wanted like

type roottype = type.gettype(reader.localname);// work if name right serializer = new xmlserializer(typeof(roottype)); // work dostuff((roottype)serializer.deserialize(xml)); // won't work  

but comments note, doesn't work @ least because can't seem use type variable conversion. while localname of xml elements does match object's local name method above requires (so far understand) assembly qualified name beast altogether. note ideal case overload dostuff method.

is there elegant solution i'm missing? or @ least solution doesn't involve endless switch statements?

same problem discussed in question how use xmlserializer deserialize object might of base or derived class without knowing type beforehand?.

my answer here


Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -