我有以下基类:
[XmlRoot("CruiseLineRequest", IsNullable = false)]
public class CruiseLineRequestMessage
{
[XmlElement(ElementName = "MessageHeader")]
public MessageHeaderType MessageHeader { get; set; }
}
正如您所见,我想调用节点 CruiseLineRequest 。我现在有一个后代:
public class DisplayBookingRequestMessage : CruiseLineRequestMessage
{
[XmlElement(ElementName = "DisplayBookingRequest")]
public DisplayBookingRequestType DisplayBookingRequestType { get; set; }
}
但是当我序列化时,我得到了:
<?xml version="1.0" encoding="utf-16"?>
<DisplayBookingRequestMessage>
<MessageHeader SegmentId="MSGHDR">
</MessageHeader>
<DisplayBookingRequest SegmentId="BKDSP1" />
</DisplayBookingRequestMessage>
,节点名为 DisplayBookingRequestMessage 。要解决这个问题,我必须在我的后代中添加与基数相同的声明:
[XmlRoot("CruiseLineRequest", IsNullable = false)]
public class DisplayBookingRequestMessage : CruiseLineRequestMessage
{
[XmlElement(ElementName = "DisplayBookingRequest")]
public DisplayBookingRequestType DisplayBookingRequestType { get; set; }
}
有什么方法可以避免添加
[XmlRoot("CruiseLineRequest", IsNullable = false)]
给我所有的后代?
答案 0 :(得分:0)
一种可能的解决方案是使用基类上的XmlInclude属性通知序列化程序有关派生类的信息,如:
[XmlRoot("CruiseLineRequest", IsNullable = false)]
[XmlInclude(typeof(DisplayBookingRequestMessage))]
public class CruiseLineRequestMessage
{
...
}
AND,然后创建序列化程序为基类类型:
XmlSerializer ser3 = new XmlSerializer(typeof(CruiseLineRequestMessage));