Specifying more than one XmlRoot attribute

I have a class used to store deserialized XML data. I want to make this class backward compatible so that it accepts the name of the old root element.

<XmlRoot(ElementName:="cancellation-response")>
Public Class ApplicantResponse
    ' properties go here!
End Class

I would like the deserializer to use this class if the root element is either a request-response or a cancel response.

<XmlRoot(ElementName:="applicant-response")>
<XmlRoot(ElementName:="cancellation-response")>
Public Class ApplicantResponse
    ' properties go here!
End Class

Is it possible?

Current Visual Studio is complaining about using the above method:

The "XmlRootAttribute" attribute cannot be used multiple times.

Thank.

+4
source share
1 answer

The solution for me was to dynamically pass the root name to the XmlSerializer:

xmlRoot = New XmlRootAttribute(myRootName)  
serializer = New XmlSerializer(GetType(ApplicantResponse), xmlRoot) 
response = CType(serializer.DeSerialize(New StringReader(serializedResponse)), ApplicantResponse)

where myRootName is either a request-response or a “cancel response”.

+3
source

Source: https://habr.com/ru/post/1692355/


All Articles