0

I want to save an object containing a value that can basically be any type. I am using XmlSerializer to do that and it works fine with one exception: If the value is an enum, the serializer stores the value as integer. If I load it back and use that value to read from a dictionary I get a KeyNotFoundException.

Is there any elegant way to save the enum as enum or to avoid the KeyNotFoundException and still use XmlSerializer? (Casting back to enum is not a good option here, the container and dictionary must support all types)

Here is a simplified piece of code that demonstrates the problem:

public enum SomeEnum
{
    SomeValue,
    AnotherValue
}

// Adding [XmlInclude(typeof(SomeEnum))] is no proper solution as Key can be any type
public class GenericContainer
{
    public object Key { get; set; }
}

private Dictionary<object, object> SomeDictionary = new Dictionary<object, object>();

public void DoSomething()
{
    SomeDictionary[SomeEnum.AnotherValue] = 123;

    var value = SomeDictionary[SomeEnum.AnotherValue];

    Save(new GenericContainer { Key = SomeEnum.AnotherValue}, "someFile.xml");
    var genericContainer = (GenericContainer)Load("someFile.xml", typeof(GenericContainer));

    // Throws KeyNotFoundException
    value = SomeDictionary[genericContainer.Key];
}

public void Save(object data, string filePath)
{
    var serializer = new XmlSerializer(data.GetType());
    using (var stream = File.Create(filePath))
    {
        serializer.Serialize(stream, data);
    }
}
public object Load(string filePath, Type type)
{
    var serializer = new XmlSerializer(type);
    using (var stream = File.OpenRead(filePath))
    {
        return serializer.Deserialize(stream);
    }
}
Arglist
  • 21
  • 4
  • You need to apply `[XmlInclude(typeof(SomeEnum))]` to your class. See [Serializing a class with a generic Enum that can be different Enum types](https://stackoverflow.com/q/43955541) and [Using XmlSerializer to serialize derived classes](https://stackoverflow.com/q/1643139). In fact this may be a duplicate, agree? – dbc Dec 07 '18 at 18:30
  • @dbc Adding XmlInclude for all possible enum types is not a solution as the Key can be any type and I don't know what types the "user" will use. – Arglist Dec 12 '18 at 13:18
  • I found the solution now, it is very simple: – Arglist Dec 12 '18 at 13:41

1 Answers1

0

You can put attributes to your enum

public enum Simple
{
      [XmlEnum(Name="First")]
      one,
      [XmlEnum(Name="Second")]
      two,
      [XmlEnum(Name="Third")]
      three,
}

Original: How do you use XMLSerialize for Enum typed properties in c#?

  • This is no solution to my problem as it only changes the string of the enum value in the XML file. But for that the enum value must be saved directly and not as an object. It is still saved as integer. – Arglist Dec 08 '18 at 02:44