0

The goal is to deserialize xml-arrayitems into my specific enum.

using System.Xml.Serialization;

public enum Example
{
    [XmlEnum(Name = "Ex1")]
    Ex1,

    [XmlEnum(Name = "Ex2")]
    Ex2
}

[XmlRoot(ElementName = "Schema", Namespace = "http://www.placeholder.com")]
public class Model
{
    [XmlArrayItem("Example")
    public List<Example> Examples;
}

It works fine as long as every element name in my xml matches one of the enum values. (as it should be)

<?xml version="1.0" encoding="UTF-8"?>
<Schema xmlns="http://www.placeholder.com" version="1">
    <Examples>
        <Example>Ex1</Example>
        <Example>Ex2</Example>
        <Example>Ex1</Example>
    </Examples>
</Schema>

However, what I want to do is deserializing any non-matching elements (e.g.: 'Ex3') into some kind of collective default value. Is there a proper way?

Things i tried:

  • declared 'Example' nullable in my model

  • added

    [XmlEnum(Name = "")] Unknown

    to the enum

Edit

    private static TXmlClass ReadXml<TXmlClass>(String filename)
    {    
        using (var reader = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            var xmlSerializer = new XmlSerializer(typeof(TXmlClass));
            return (TXmlClass)xmlSerializer.Deserialize(reader);
        }
    }
aleX
  • 59
  • 1
  • 7
  • Can you please share with the actual deserialization logic as well? – Peter Csala May 13 '22 at 13:59
  • There are no non-matching values. Enums are essentially labels for integer values. They don't limit what values can be passed. You can pass 1234 instead of one of the enum values and the compiler won't complain. – Panagiotis Kanavos May 13 '22 at 14:24
  • @PanagiotisKanavos the compiler doesn't complain, but xml-serializer throws an exception at runtime: 'Ex3 is not a valid value for Example' – aleX May 13 '22 at 14:37
  • You may need to use some sort of surrogate array property. I don't think there's any way to make XmlSerializer fall back to a default value for an unknown enum. See e.g. [XmlSerializer with new enum values](https://stackoverflow.com/q/1621306) or [Handling extra spaces when deserializing XML values to enums](https://stackoverflow.com/q/1621306). – dbc May 13 '22 at 14:55

0 Answers0