Get XmlEnumAttribute value for an Enum field in C#
Sometimes, we have to convert an Enum back to its original Xml value, after google the solution, I fond it is not hard to implement, and share it here
Method
public static string ConvertToString(Enum e)
{
// Get the Type of the enum
Type t = e.GetType();
// Get the FieldInfo for the member field with the enums name
FieldInfo info = t.GetField(e.ToString("G"));
// Check to see if the XmlEnumAttribute is defined on this field
if (!info.IsDefined(typeof(XmlEnumAttribute), false))
{
// If no XmlEnumAttribute then return the string version of the enum.
return e.ToString("G");
}
else
{
// Get the XmlEnumAttribute
object[] o = info.GetCustomAttributes(typeof(XmlEnumAttribute), false);
XmlEnumAttribute att = (XmlEnumAttribute)o[0];
return att.Name;
}
}
A demo of how to use this method
static void Main()
{
// Get the XmlEnumAttribute
Console.WriteLine(ConvertToString(TestEnumClass.Three));
Console.WriteLine(ConvertToString(TestEnumClass.Two));
}
public enum TestEnumClass
{
One = 1,
Two = 2,
[System.Xml.Serialization.XmlEnum("The Third one")]
Three = 3,
}
