Monday, February 20, 2006

 

Getting the XmlEnum value of an Enum for XML serialization

Getting the XmlEnum value of a property is something Serialization does easily, but doing it yourself is quite a challenge.

I was happy when I finally Googled this post as it enabled me to write this function to determine the Xml value to return.

The key is to know that an Enum's values are treated as Fields within the Enum. You can then enumerate the fields using GetFields() and search for the field with the value matching your object.

Public Function GetXmlEnumValue(ByVal o As Object) As String
'Enumerate the values of the EnumType of this object
For Each enumValue As FieldInfo In o.GetType.GetFields(BindingFlags.Public Or BindingFlags.Static)
'If this value matches our object, we have the correct
If enumValue.GetValue(Nothing) = o Then
'Search for XmlEnumAttributes (there should only be one)
Dim xmlatt As Xml.Serialization.XmlEnumAttribute = _
CType(Attribute.GetCustomAttribute(enumValue, _
GetType(Xml.Serialization.XmlEnumAttribute)), _
Xml.Serialization.XmlEnumAttribute)
Return xmlatt.Name
End If
Next
'Not found
Return Nothing
End Function



Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?