XmlSerializer - How to set the default value when deserializing an enumeration?

I have a class that looks like this (greatly simplified):

public class Foo { public enum Value { ValueOne, ValueTwo } [XmlAttribute] public Value Bar { get; set; } } 

I get an xml file from an external source. Their documentation states that the Foo element will only have a ValueOne or ValueTwo value in the Bar attribute (they do not provide an XSD).

So, I deserialize it as follows:

  var serializer = new XmlSerializer(typeof(Foo)); var xml = "<Foo Bar=\"ValueTwo\" />"; var reader = new StringReader(xml); var foo = (Foo)serializer.Deserialize(reader); 

... and everything works.

However, last night they sent me some XML similar to this, and my deserialization failed (as it should be): <Foo Bar="" />

Is there a good way to protect the code around this? Ideally, I would like to say something like "default ValueOne if something goes wrong." I do not want to throw away the whole XML file because one attribute is distorted.

+4
source share
2 answers

you can specify enum like this, so this will set the enumeration value "" to Unknown = 0, as the default value

 public enum Foo { [XmlEnum(Name = "")] Unknown =0, [XmlEnum(Name = "Single")] One, [XmlEnum(Name = "Double")] Two } 

more detailed check: XmlEnumAttribute class

+4
source

Shoot down the XmlSerializer .. Use LINQ2XML for this simple task

 XElement doc=XElement.Load("yourStreamXML"); List<Foo> yourList=doc.Descendants("Foo") .Select(x=> new Foo { Bar=(Enum.GetNames(typeof(Value)).Contains(x.Attribute("Bar").Value))?((this.Value)x.Attribute("Bar")):(this.Value.ValueOne); } ).ToList<Foo>(); 

So, I basically do this

 if(Enum.GetNames(typeof(Value)).Contains(x.Attribute("Bar").Value)) //if the xml bar value is a valid enum Bar=(this.Value)x.Attribute("Bar"); else//xml bar value is not a valid enum..so use the default enum i.eValueOne Bar=this.Value.ValueOne; 
0
source

Source: https://habr.com/ru/post/1443245/


All Articles