0

Is it possible to use the KnownType's class name as the tag, rather then the parent classes? e.g.

This is an excerpt from a larger DataContract xml file,

[DataContract (Namespace = "projectNamespace")]
[KnownType(typeof(Warning)), KnownType(typeof(Error))]
public abstract class Message
{
    protected Message(LogLevel logLevel, int percentUsed, string message)
    {
        this.LogLevel = logLevel;
        this.LogMessage = message;
        this.Percent = percentUsed;
    }

    internal readonly LogLevel LogLevel;
    [DataMember] internal readonly int Percent;    
    [DataMember] internal readonly string LogMessage;
}

[DataContract (Name="Warning", Namespace = "projectNamespace")]
internal sealed class Warning : Message
{
    public Warning(int percentUsed, string message) : base(LogLevel.Warn, percentUsed, message)
    {
    }
}

[DataContract(Name = "Error", Namespace = "projectNamespace")]
internal sealed class Error : Message
{
    public Error(int percentUsed, string message) : base(LogLevel.Error, percentUsed, message)
    {
    }
}

public enum LogLevel
{
    Warn, Error
}

What I saw:

<messages>
  <Message i:type="Warning">
    <PercentUsed>75</PercentUsed>
    <LogMessage>75% used</LogMessage>
  </Message>
  <Message i:type="Error">
    <PercentUsed>100</PercentUsed>
    <LogMessage>0% remaining</LogMessage>
  </Message>
</messages>

Expected:

<messages>
  <Warning>
    <PercentUsed>75</PercentUsed>
    <LogMessage>75% used</LogMessage>
  </Warning>
  <Error>
    <PercentUsed>100</PercentUsed>
    <LogMessage>0% remaining</LogMessage>
  </Error>
</messages>

Note how the Message has an annoying i:type="Error" rather then just being a <Error>

Ryan Leach
  • 4,262
  • 5
  • 34
  • 71
  • 1
    I believe `DataContractSerializer` only supports the `KnownType` mechanism, which is equivalent to `[XmlInclude]` with `XmlSerializer`. There's no data contract equivalent to the [`[XmlElement(Type = typeof(ChildA))]`](https://stackoverflow.com/questions/1643139/using-xmlserializer-to-serialize-derived-classes) technique of `XmlSerializer` for handling polymorphism. – dbc Jan 31 '18 at 05:01
  • @dbc as far as I can tell, you are correct. I ended up just ignoring it. – Ryan Leach Feb 21 '18 at 01:59
  • 1
    Note to others following this code, it currently has a bug where the base constructors are never called, due to DCS, you need to create a deserialization callback – Ryan Leach Mar 02 '18 at 00:08

0 Answers0