deserializing enums

ぐ巨炮叔叔 提交于 2019-12-17 16:32:45

问题


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


回答1:


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);
        }
    }
}



回答2:


You probably need to mark up your enumeration, and add a default item that represents Unknown.

For example:

Public Enum EmployeeStatus
   <XmlEnum("")> Unknown = 0
   <XmlEnum("Single")> One = 1
   <XmlEnum("Double")> Two = 2
   <XmlEnum("Triple")> Three = 3
End Enum

For more information, see here.




回答3:


You can do it this way:

namespace Example
{

   public enum Language
   {
     [XmlEnum("en")]
     English,

     [XmlEnum("de")]
     Deutsch
   }

   public class ExampleClass
   {

      private Language? language;

      [XmlAttribute("Language")]
      public Language Language
      {
         get { return language ?? Example.Language.English; }
         set { language = value; }
      }

      .
      .
      .
   }
}



回答4:


What would you want the result to be ?

A blank value cannot be mapped to a null reference since an enum is a non-nullable value type.




回答5:


object wontBeNull = couldBeNull ?? defaultIfNull;

Is what I'd try. It's called Null-Coalescing operator, I use it when I want a default for null input.



来源:https://stackoverflow.com/questions/4250656/deserializing-enums

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!