c# - How do I use an XmlSerializer to deserialize an object that might be of a base or derived class without knowing the type beforehand? -


in c#, how use xmlserializer deserialize object might of base class, or of of several derived classes without knowing type beforehand?

all of derived classes add additional data members. i've made simple gui can serialize , deserialize class objects. serialize objects whatever inherited class (or base class) appropriate based on fields user chooses populate.

i have no issues serialization; problem deserialization. how can possibly have xmlserializer deserialize data correct derived class without knowing class beforehand? create xmlreader read first node of xml file , determine class it, , seems work purposes, seems extremely inelegant solution.

i've posted sample code below. suggestions?

basetype objectofconcern = new basetype(); xmlserializer xserializer; xmltextreader xtextreader = new xmltextreader(default_filename);  { xtextreader.read(); } while (xtextreader.nodetype != xmlnodetype.element);  string objecttype = xtextreader.name; xtextreader.close();  filestream fstream = new filestream(default_filename, filemode.open);  switch (objecttype)     { case "type1":     xserializer = new xmlserializer(typeof(derivedtype));      objectofconcern = (derivedtype)xserializer.deserialize(fstream);      //load fields specific derived type here     whatever = (objectofconcern derivedtype).noofstreamubordinates.tostring();      case "xxx_1":         //code here      case "xxx_2":         //code here      case "xxx_n":         //code here          //and forth      case "basetype":     xserializer = new xmlserializer(typeof(basetype));     assigneventhandler(xserializer);     objectofconcern = (basetype)xserializer.deserialize(fstream); }  //assign deserialized values base class common derived classes here  //close filestream fstream.close(); 

have root class/tag contains derived types? if yes, can use xmlelementattribute map tag name type:

public class rootelementclass {     [xmlelement(elementname = "derived1", type = typeof(derived1basetype))]     [xmlelement(elementname = "derived2", type = typeof(derived2basetype))]     [xmlelement(elementname = "derived3", type = typeof(derived3basetype))]     public basetype myproperty { get; set; } }  public class basetype { } public class derived1basetype : basetype { } public class derived2basetype : basetype { } public class derived3basetype : basetype { } 

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#? -