Question

I have a problem on XMLSerialzation with CSharp again. I have an enumeration that is serialized using the [System.Xml.Serialization.XmlEnumAttribute]-attribute.

public enum anEnum {
    [System.Xml.Serialization.XmlEnumAttribute("Wohnbaufläche")]
    Wohnbauflaeche,
    ...
}

So now I want to use the value of this attribute within my application. Is there a way I can read it (e.g. the "Wohnbaufläche") when I have an enum-value?

anEnum a = Wohnbauflaeche;
string value = getValueFromEnum(a);

How should this method getValueFromEnum should look like to retrieve the string-representation of the enum?

Thanks in advance

Was it helpful?

Solution

  var type = typeof(anEnum);
  var memInfo = type.GetMember(anEnum.Wohnbauflaeche.ToString());
  var attributes = memInfo[0].GetCustomAttributes(typeof(XmlEnumAttribute),
      false);
  var value= ((XmlEnumAttribute)attributes[0]).Name;

OTHER TIPS

Lots of reflection, basically:

var name = (from field in typeof(anEnum).GetFields(
   System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public)
     where field.IsLiteral && (anEnum)field.GetValue(null) == a
     let xa = (System.Xml.Serialization.XmlEnumAttribute)
         Attribute.GetCustomAttribute(field,
         typeof(System.Xml.Serialization.XmlEnumAttribute))
     where xa != null
     select xa.Name).FirstOrDefault();

Personally, I'd cache them all in a Dictionary<anEnum,string> - something like:

anEnum a = anEnum.Wohnbauflaeche;
string name = a.GetName();

using:

public static class EnumHelper 
{
    public static string GetName<T>(this T value) where T : struct
    {
        string name;
        return Cache<T>.names.TryGetValue(value, out name) ? name : null;
    }
    private static class Cache<T>
    {
        public static readonly Dictionary<T, string> names = (
                   from field in typeof(T).GetFields(
                       System.Reflection.BindingFlags.Static | 
                       System.Reflection.BindingFlags.Public)
                   where field.IsLiteral
                   let value = (T)field.GetValue(null)
                   let xa = (System.Xml.Serialization.XmlEnumAttribute)
                       Attribute.GetCustomAttribute(field,
                       typeof(System.Xml.Serialization.XmlEnumAttribute))
                   select new
                   {
                       value,
                       name = xa == null ? value.ToString() : xa.Name
                   }
                ).ToDictionary(x => x.value, x => x.name);
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top