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.
Neild source share