Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize/deserialize optional XML enumeration in C#?

I am trying to figure out how to serialize/deserialize an XML listing to C# that has an optional attribute that is an enumerated type. The following is my C# class:

public class AttributeAssignmentExpressionElement : XACMLElement
{
    [XmlAttribute]
    public string AttributeId { get; set; }

    [XmlAttribute]
    public Category Category { get; set; }                   
}

My Category enumeration is defined as follows:

public enum Category
{
    [XmlEnum(Name = "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject")]
    Subject,
    [XmlEnum(Name = "urn:oasis:names:tc:xacml:3.0:attribute-category:resource")]
    Resource,
    [XmlEnum(Name = "urn:oasis:names:tc:xacml:3.0:attribute-category:action")]
    Action,
    [XmlEnum(Name = "urn:oasis:names:tc:xacml:3.0:attribute-category:environment")]        
    Environment
}  

When Category is present in the corresponding XML file, serialization/deserialization works as expected. However if the Category is missing from the XML, the default value is used (first item in the enumeration). If I try to make the enumerated variable nullable (Category?), the deserializer throws an exception because it is unable to deserialize a complex type. Given the following XML (which does not contain the attribute), how can I serialize the enumeration appropriately?

<AttributeAssignmentExpression
    AttributeId="urn:oasis:names:tc:xacml:3.0:example:attribute:text">       
</AttributeAssignmentExpression>

In this situation, the value in the deserialized object should be null.

Thanks for any help you can offer!

like image 245
Rockdocta Avatar asked May 31 '12 19:05

Rockdocta


1 Answers

Well, you can do this - but it is a bit messy:

[XmlIgnore]
public Category? Category { get; set; }

[XmlAttribute("Category")]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public Category CategorySerialized
{
    get { return Category.Value; }
    set { Category = value; }
}
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeCategorySerialized()
{
    return Category.HasValue;
}

What this does:

  • uses a Category? for the optional enum value
  • disables the Category property for serialization
  • adds a secondary property, CategorySerialized, as a proxy to Category, which is non-nullable and hidden (as far as is possible) from the IDE etc
  • use conditional serialization on CategorySerialized via the ShouldSerialize* pattern
like image 186
Marc Gravell Avatar answered Sep 22 '22 06:09

Marc Gravell