简体   繁体   中英

Inherit xml serialization attribute in descendant c# classes

I have the following base class:

[XmlRoot("CruiseLineRequest", IsNullable = false)]
public class CruiseLineRequestMessage
{
    [XmlElement(ElementName = "MessageHeader")]
    public MessageHeaderType MessageHeader { get; set; }
}

and as you can see I want to call the node CruiseLineRequest . I now have a descendant:

public class DisplayBookingRequestMessage : CruiseLineRequestMessage
{
    [XmlElement(ElementName = "DisplayBookingRequest")]
    public DisplayBookingRequestType DisplayBookingRequestType { get; set; }
}

but when I serialize that I get:

<?xml version="1.0" encoding="utf-16"?>
<DisplayBookingRequestMessage>
  <MessageHeader SegmentId="MSGHDR">
  </MessageHeader>
  <DisplayBookingRequest SegmentId="BKDSP1" />
</DisplayBookingRequestMessage>

and the node is called DisplayBookingRequestMessage . To fix this means I have to add the same declaration as the base in my descendant:

[XmlRoot("CruiseLineRequest", IsNullable = false)]
public class DisplayBookingRequestMessage : CruiseLineRequestMessage
{
    [XmlElement(ElementName = "DisplayBookingRequest")]
    public DisplayBookingRequestType DisplayBookingRequestType { get; set; }
}

Is there any way I can avoid having to add

[XmlRoot("CruiseLineRequest", IsNullable = false)]

to all my descendants?

One possible solution is to inform the serializer about the derived class by using the XmlInclude attribute on the base class like:

[XmlRoot("CruiseLineRequest", IsNullable = false)]
[XmlInclude(typeof(DisplayBookingRequestMessage))]    
public class CruiseLineRequestMessage
{
    ...
}

AND, then create the serializer to be of base class type:

XmlSerializer ser3 = new XmlSerializer(typeof(CruiseLineRequestMessage));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM