Getting the XmlEnumAttribute value for an Enum field

I recently had to convert an Enum back to its original Xml value so I thought I’d share the little method I wrote with you all incase you wondered how to do it yourself.


public static string ConvertToString(Enum e)
// Get the Type of the enum
Typet = 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");

// Get the XmlEnumAttribute
object[] o = info.GetCustomAttributes(typeof(XmlEnumAttribute), false);
XmlEnumAttribute att = (XmlEnumAttribute)o[0];
return att.Name;

Example Enum Class

public enum TestEnumClass
FirstValue = 1,
SecondValue = 2,
[System.Xml.Serialization.XmlEnum("The Third one")]
ThirdValue = 3

Example usage

An Enum of TestEnumClass.FirstValue will then return “FirstValue”, while TestEnumClass.ThirdValue will return “The Third one”.

Hope you find that useful.

[tags]microsoft, .net, code, programming, sample, c#[/tags]

1 thought on “Getting the XmlEnumAttribute value for an Enum field”

Comments are closed.