I would like to control Xml serialization over each item of a List, suppose you have this :
public class Item {
[XmlElement("id")]
public int Id { get; set; }
[XmlElement("label")]
public string Label { get; set; }
#region Conditional serialization
public bool ShouldSerializeLabel()
{
return !string.IsNullOrEmpty(Label);
}
#endregion
}
public class Root {
[XmlArray("items")]
[XmlArrayItem("item")]
public List<Item> Items { get; set; }
#region Conditional serialization
// Suppose I have two items but one has no label,
// How to avoid this :
// <items>
// <item>
// <id>5</id>
// <label>5</label>
// </item>
// <item> // I don't want items without label in my collection, how to tell the XmlSerializer not to serialize them
// <id>4</id>
// </item>
// </items>
//
// But I still want to have to possibility to do that :
// <product>
// <item> // this item has no label and it's ok
// <id>42</id>
// </item>
// <price>1.99</price>
// </product>
#endregion
}
How to tell that an Item with string.IsNullOrEmpty(Label) should not be serialized in my collection ? My workaround is to clean the list of Item before Serializing, but is there a way to do this declaratively ?