Deserializing derived classes

cjard

Well-known member
Joined
Apr 25, 2006
Messages
7,081
Programming Experience
10+
I read that XmlSerializer has a constructor for (Type, Type() )

The array is used to specify extra types to deserialize. XmlSer doesnt seem to try very hard when deserializing an inheritance hierarchy though


Suppose we have xmls:

VB.NET:
<request foo="bar">
  <abc>blah</abc>
</request>

<request foo="bar">
  <def>blah</def>
</request>

And classes:
VB.NET:
<XmlRoot("request")>_
Class Request
  <XmlAttribute("foo")>
  Public Property Foo As String ...
End Class

Class AbcRequest  Inherits Request
    <XmlElement("abc")>_
  Public Property Abc As String ...
End Class

Class DefRequest  Inherits Request
    <XmlElement("def")>_
  Public Property Def As String ...
End Class

If I make my XmlSerializer like this (pseudocode, actually from C#):

XmlSerializer(typeof(Request), new Type() { typeof(AbcRequest), typeof(DefRequest) } )


Then it only deserializes and creates a Request, rather than looking deeper and finding the aspects of AbcRequest or DefRequest and creating one of those

Is there any way I can get my inherited hierarchy of classes, and have XmlSerializer find the best class to deserialize into?

If not, I'll end up doing:

VB.NET:
If xmlString.Contains("<abc") Then 
  ... XmlSerializer(typeof(AbcRequest))
Else If
 ...

Note I cannot use xsi:type because I have no power to alter the xml
 
Back
Top