XmlSerializer + Polymorphism

Given the (contrived) base class and subclass that we want to serialize through WCF using XmlSerializer. We decorate the collection (see Answer Class) in accordance with the article:

http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlelementattribute.aspx (see comments section).

The problem is that although it seems that the correct WSDL is being created, SVCUtil generates a class file in which the GetUserResponse class contains a property called Items. Is this related to applying [XmlElement] to an array? Although the XmlArray element does not have a Type property.

Thanks in advance.

[Serializable]
[XmlType]
public class UserBase
{
    public int Id {get;set;}
}

[Serializable]
[XmlType]
public class BasicUser : UserBase
{
    public string UserName {get;set;}
}

[Serializable]
[XmlType]
public class SuperUser : UserBase
{
    public string UserName {get;set;}
    public bool SpecialLevel {get;set;}

}

[Serializable]
[XmlType]
public class GetUserResponse
{
    [XmlElement("Users", typeof(User)), XmlElement("SuperUsers", typeof(SuperUser))]
    public List<UserBase> Users {get;set;}
}
+3
source share
1 answer

[XmlElement] , xml :

<GetUserResponse>
    <Users>{this is a user}</Users>
    <Users>{this is a user}</Users>
    <SuperUsers>{this is a super user}</SuperUsers>
    <Users>{this is a user}</Users>
    <SuperUsers>{this is a super user}</SuperUsers>
</GetUserResponse>

, , Items. , :

[XmlArray("Users")]
[XmlArrayItem("User", typeof(User))]
[XmlArrayItem("SuperUser", typeof(SuperUser))]

:

<GetUserResponse>
    <Users>
        <User>{this is a user}</User>
        <User>{this is a user}</User>
        <SuperUser>{this is a super user}</SuperUser>
        <User>{this is a user}</User>
        <SuperUser>{this is a super user}</SuperUser>
    </Users>
</GetUserResponse>

Users.

+7

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


All Articles