0

Given the classes:

class Base { } class Derived : Base { public string Value { get; set; } }

With this XML: <Derived><Value>something</Value></Derived>

Is there a way to create a serializer that can deserialize this only knowing the base class:

var serializer = new XmlSerializer(typeof(Base)); var b = (Base)serializer.Deserialize(stream);

I know how to deal with polymorphic sub elements but not the root element its self.

I feel like this question must have been asked before but I'm not finding the answer so a link to an answer would more than enough :)

jazb
  • 5,498
  • 6
  • 37
  • 44
Eli Pulsifer
  • 713
  • 9
  • 25
  • possible duplicate: https://stackoverflow.com/questions/28086893/how-to-do-a-polymorphic-deserialization-in-c-sharp-given-a-xsd – jazb Nov 29 '18 at 02:52
  • Just want to add that I have no control over the xml format, this is being used to parse an xml messaging protocol and message type must be identified by the root element name. – Eli Pulsifer Nov 29 '18 at 02:53
  • @JohnB Yes, that would work and it may be my only option but I was hoping not to have to parse the xml twice. Seems like a waste to parse the XML once to get the root element name, map that to a serializer and then reparse the xlm again to deserialize into an object. – Eli Pulsifer Nov 29 '18 at 02:58

0 Answers0