Search code examples
c#xml-deserialization

Instance validation error: * is not a valid value for *


I'm trying to deserialize an XML string, where the value of an element, ain't within the scope of my Enum values.

Public enum MyEnum
{
    Unknown,
    Car,
    Bicycle,
    Boat
}

[SerializableAttribute()]
public class MyClass
{
    private string _id;
    private MyEnum _myEnum;

    public string ID
    {
        get { return _id; }
        set { _id = value; }
    }

    public MyEnum EnumValue
    {
        get { return _myEnum; }
        set { _myEnum = value; }
    }

    public MyClass(string id)
    {
        this._id = id;
    }

    public MyClass() : this("") { }
}

If I try to deserialize following string (note Plane as enum value):

<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><MyClass><ID>1234567890123456789</ID><EnumValue>Plane</EnumValue></MyClass>

then my deserialize will thrown an exception, before it even hit my public field for EnumValue, with following exception message:

Instance validation error: 'Plane' is not a valid value for EnumValue

Is it possible to return a default value for EnumValue, if the value I try to parse in the XML ain't supported as a EnumValue?? Eg. in the case of the XML string provided here, the EnumValue should be set as 'Unknown'.


Solution

  • [XmlIgnore]
    public MyEnum EnumValueReal
    {
        get { return _myEnum; }
        set { _myEnum = value; }
    }
    
    public string EnumValue
    {
         get
         {
             return EnumValueReal.ToString();
         }
    
         set
         {
             MyEnum result = MyEnum.Unknown;
             Enum.TryParse(value, true, out result);
    
             EnumValueReal = result;
         }
    }