Peter
Peter

Reputation: 1687

Xml.Serialization multiple types for an object

I have this Property and want to use it like this:

public class XmlValue : INullable
{
    [XmlElement("IpAdress", typeof(IpClass))]
    [XmlElement("FileValue", typeof(FileClass))]
    [XmlElement("StringValue", typeof(string))]
    public object Value { get; set; }

    public bool IsNull => Value == null;
}

So there are different fields in my nested Xml-Class for public object Value. But there will be only one of the possibles elements (IpAdress,FileValue and StringValue) available at once.

The actual code just kills my object deserialization with null.

How can I make it work that i only need one property?

Upvotes: 1

Views: 1529

Answers (1)

burning_LEGION
burning_LEGION

Reputation: 13450

Use three different classes with IpClass, FileClass and string field. Otherwise You should customize serialization

Use attribute [XmlInclude(typeof(YourClass))] on base class to declare dirived classes.

[XmlInclude(typeof(IpClass))]
[XmlInclude(typeof(FileClass))]
[XmlInclude(typeof(StringValue))]
public abstract class AbstractValue : INullable
{   
    public virtual bool IsNull => Value == null;
}
public sealed class IpValue : AbstractValue
{   
    public IpClass Value { get; set; }
}
public sealed class FileValue : AbstractValue
{   
    public FileClass Value { get; set; }
}
public sealed class StringValue : AbstractValue
{   
    public string Value { get; set; }
}

Upvotes: 1

Related Questions