Search code examples
c#xml-serialization

How can I have a nullable enum serialized to an attribute


I have a class that I need to deserialize from xml, and it has an enum property that is stored as an attribute in the xml. Sometimes this attribute can be missing or have "" as a value. How can I have the serializer deal with making the BorrowerResidencyType property nullable?

XML:

<_RESIDENCE _StreetAddress="" _City="San Jose" _State="CA" BorrowerResidencyType="" />
<_RESIDENCE _StreetAddress="" _City="San Jose" _State="CA"  />

C#:

[System.CodeDom.Compiler.GeneratedCodeAttribute ( "System.Xml", "4.0.30319.17929" )]
[System.SerializableAttribute ()]
[System.Xml.Serialization.XmlTypeAttribute ( AnonymousType = true )]
public enum _RESIDENCEBorrowerResidencyType
{

    /// <remarks/>
    Current,

    /// <remarks/>
    Prior,
}

public class Test{
public string StreetAddress{get;set;}
public string City{get;set;}
[System.Xml.Serialization.XmlAttributeAttribute ()]
public _RESIDENCEBorrowerResidencyType BorrowerResidencyType{get;set;}
}

Is there another library that would handle this situation more intelligently?


Solution

  • Maybe something like:

    public enum _RESIDENCEBorrowerResidencyType
    {
        [XmlEnum(Name="")]
        Default = 0,
    
        Current,
        Prior
    }