Search code examples
c#attributespropertiesxml-serialization

Declare [XmlElement(IsNullable = true)] at class level


Is there a way to declare [XmlElement(IsNullable = true)] at class level so that all properties in the class will be XML serialized, even if they are null?

e.g.

public BankAccount BankAccount { get; set; }

Should result in <BankAccount xsi:nil="true" />, rather than the default missing element.

I tried this but the compiler (correctly) states that the attribute is not valid for class declarations.

The reason for this is that I don't want to have to specify this for all properties.


Edit: This is the serialization method I am using:

        var serializer = new XmlSerializer(FormType);
        var stream = new MemoryStream();

        serializer.Serialize(stream, form);

Solution

  • Unfortunately you have to be explicit when annotating your class for XML serialization. Each property must be annotated with its own XmlElement attribute unless you want a default behaviour.