Search code examples
c#xml-serialization

XML Serialization and empty collections


I have a a property defined as:

[XmlArray("delete", IsNullable = true)]
[XmlArrayItem("contact", typeof(ContactEvent)),
 XmlArrayItem("sms", typeof(SmsEvent))]
public List<Event> Delete { get; set; }

If the List<> Delete has no items

<delete />

is emitted. If the List<> Delete is set to null

<delete xsi:nil="true" />

is emitted. Is there a way using attributes to get the delete element not to be emitted if the collection has no items?

Greg - Perfect thanks, I didn't even read the IsNullable documentation just assumed it was signalling it as not required.

Rob Cooper - I was trying to avoid ISerializable, but Gregs suggestion works. I did run into the problem you outlined in (1), I broke a bunch of code by just returning null if the collection was zero length. To get around this I created a EventsBuilder class (the class I am serializing is called Events) that managed all the lifetime/creation of the underlying objects of the Events class that spits our Events classes for serialization.


Solution

  • If you set IsNullable=false or just remove it (it is false by default), then the "delete" element will not be emitted. This will work only if the collection equals to null.

    My guess is that there is a confusion between "nullability" in terms of .NET, and the one related to nullable elements in XML -- those that are marked by xml:nil attribute. XmlArrayAttribute.IsNullable property controls the latter.