'how to deserialize xml arrayItems in enum if there are unrecognized elements
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);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|