序列化保持层次结构树的类

时间:2013-04-02 21:47:52

标签: c# xml serialization

我想序列化类层次结构并将层次结构树保留在生成的xml中。我设置了ProtokolMessage类的Message属性 使用Heartbeat对象实现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中获得层次结构树吗?

1 个答案:

答案 0 :(得分:1)

时间没有显示,因为它是受保护的财产。

如果您将其更改为公开,则可以正确地看到该元素。

<?xml version="1.0" encoding="utf-16"?>
<protocol xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <name>someName</name>
  <messageID>1101</messageID>
  <Message xsi:type="Heartbeat">
    <time>2013-04-02T15:09:36</time>
  </Message>
</protocol>

如果你将ElementName设置为上面的“heartbeat”,它将起作用,但我认为如果你有不同类型的消息,它们可能不适合你,它们将始终设置为“心跳”。

[XmlElement(ElementName = "heartbeat")]
public Message Message { get; set; }