我想序列化类层次结构并将层次结构树保留在生成的 xml 中。我用实现 Message 抽象类的 Heartbeat 对象设置了 ProtokolMessage 类的 Message 属性。作为输出结果,我想得到以下 xml:
<protocol>
<name>someName</name>
<messageId>1101</messageId>
<heartbeat>
<time>2013-04-02T17:35:55</time>
</heartbeat>
</protocol>
然而生成的 xml 是:
<protocol>
<Message xsi:type="heartbeat" />
<name>someName</name>
<messageID xmlns="Message">1101</messageID>
</protocol>
领域模型:
[XmlRoot("protocol")]
public class ProtocolMessage
{
[XmlElement(ElementName = "name")]
public string Name { get; set; }
[XmlElement(ElementName = "messageID")]
public string MessageID { get; set; }
public Message Message {get; set;}
public ProtocolMessage()
{}
}
[XmlInclude(typeof(Heartbeat))]
public abstract class Message
{
public Message()
{ }
}
[XmlType(TypeName = "heartbeat")]
public class Heartbeat : Message
{
[XmlElement("time")]
protected string Time { get; set; }
public Heartbeat()
: this(DateTime.Now)
{
}
public Heartbeat(DateTime dateTime)
{
Time = dateTime.ToString("s");
}
}
public class Program
{
static void Main(string[] args)
{
var protocolMsg = new ProtocolMessage
{
Name = "someName",
MessageId = "1101",
Message = new Heartbeat();
};
var serializer = new XmlSerializer(typeof(ProtocolMessage));
StringWriter sw = new StringWriter();
serializer.Serialize(sw, this);
}
}
我可以在xml中获取层次结构树吗?