Thursday, July 17, 2008

Get the XmlEnum Value for an Enum

When you serialize an enumeration (Enum in VB.NET, enum in C#), by default the XML string representation of the enumerated member is the name of the enumeration member (i.e. the same as calling the ToString function of the enumeration member). For example, if the Color property of the following object was set to Green, the XML representation of that property would be <Color>Green</Color>:

Public Enum PrimaryColor
    Invalid = 0
    Red = 1
    Green = 2
    Blue = 3
End Enum

<Serializable()> _
Public Class Sample

   
Public Property Color() As PrimaryColor
        Get
            Return mColor
        End Get
        Set(ByVal value As PrimaryColor)
            mColor = value
        End Set
    End Property
    Private mColor As PrimaryColor

End
Class

This default behavior can be modified using the XmlEnumAttribute Class. For example, if the enumeration defined above was changed as shown below, the XML representation of the Color property would be <Color>G</Color>.

Public Enum PrimaryColor
    Invalid = 0
    <System.Xml.Serialization.XmlEnum("R")> _
    Red = 1
    <System.Xml.Serialization.XmlEnum("G")> _
    Green = 2
    <System.Xml.Serialization.XmlEnum("B")> _
    Blue = 3
End Enum

Even with the new XmlEnum values applied to the enumeration members, the ToString function will still return the name of the enumeration member, not the XmlEnum value. The following function will take an enumeration value and return its XML string value (either the XmlEnum value, if present, or the ToString value):

Public Shared Function ToXmlString( _
    ByVal value As [Enum]) As String

    Dim XmlEnumAttributes() As _
        System.Xml.Serialization.XmlEnumAttribute
    Dim EnumFieldInfo As System.Reflection.FieldInfo

   
' Verify Input Arguments
    If value Is Nothing Then
        Throw New ArgumentNullException("value")
    End If

    ' Get the Field Information for the 
    '
enumeration member
    EnumFieldInfo = _ 
        value.GetType().GetField(value.ToString())

    ' Get the XmlEnum attributes for the 
    ' enumeration member
    XmlEnumAttributes = CType( _
        EnumFieldInfo.GetCustomAttributes( _
        GetType(System.Xml.Serialization.XmlEnumAttribute), True), _
        System.Xml.Serialization.XmlEnumAttribute())

    ' Check to see if an XmlEnum attribute was found
    If XmlEnumAttributes.Length < 1 Then
        ' Return the default value
        Return value.ToString()
    Else
        ' Return the XmlEnum value
        Return XmlEnumAttributes(0).Name
    End If

End Function