I have an xml in which one of the elements has an attribute that can be blank. For e.g.,
<tests>
<test language="">
.....
</test>
</tests>
Now, language is enum type in the classes created from the schema. It works fine if the language is specified, it fails to deserialize if it is blank (as shown in example).
Edit: Code for deserialization:
XmlSerializer xmlserializer = new XmlSerializer(type);
StringReader strreader = new StringReader(stringXML);
Object o = serializer.Deserialize(strreader);
How can I handle this scenario
You could declare the enum property as nullable:
public Language? Language { get; set; }
EDIT: ok, I just tried, it doesn't work for attributes... Here's another option: don't serialize/deserialize this property directly, but serialize a string property instead :
[XmlIgnore]
public Language Language { get; set; }
[XmlAttribute("Language")]
public string LanguageAsString
{
get { return Language.ToString(); }
set
{
if (string.IsNullOrEmpty(value))
{
Language = default(Language);
}
else
{
Language = (Language)Enum.Parse(typeof(Language), value);
}
}
}