Maxim
Maxim

Reputation: 4214

Serialize classes keeping hierarchy tree

I want to serialize class hierarchy and keep hierarchy tree in resulting xml. I set Message property of ProtokolMessage class with Heartbeat object which implements Message abstract class. As the output result I want to get following xml:

<protocol>
    <name>someName</name>
    <messageId>1101</messageId>
    <heartbeat>
             <time>2013-04-02T17:35:55</time>
    </heartbeat>
</protocol>

However resulting xml is:

<protocol>
    <Message xsi:type="heartbeat" />
    <name>someName</name>
    <messageID xmlns="Message">1101</messageID>
</protocol>

Domain model:

[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);
    }
}

Can I get hierarchy tree in xml?

Upvotes: 1

Views: 1589

Answers (1)

Kyle C
Kyle C

Reputation: 1637

time isn't showing because it's a protected property.

if you change that to public you see that element properly.

<?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>

if you set the ElementName to "heartbeat" above Message it will work, but I think this might not work for you if you have different types of Messages they will always be set to "heartbeat".

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

Upvotes: 1

Related Questions