2

I would like to know if one can conditionally exclude items in a list from being serialized using the ShouldSerialize* pattern. For example take the two classes:

public class Product{
   public int ID {get; set;}
   public List<Styles> ProductSyles {get; set;}
}

public class Styles{
   public int ID {get; set;}
   public bool Selected {get; set;}
   public string StyleName {get; set;}
}

Can I go about only serializing the items in the ProductStyles property with .Selected = true? Is this possible using the ShouldSerialize* pattern

slugster
  • 49,403
  • 14
  • 95
  • 145
Neomoon
  • 181
  • 1
  • 3
  • 12
  • 1
    Make the list private then create a public property that filters the list that before returning results. – jdweng Nov 16 '16 at 19:21

1 Answers1

1

XmlSerializer has no built-in functionality to omit selected collection entries during serialization. The quickest way to implement this would be to use a surrogate array property, like so:

public class Product
{
    public int ID { get; set; }

    [XmlIgnore]
    public List<Styles> ProductSyles { get; set; }

    [XmlArray("ProductStyles")]
    public Styles [] SerializableProductSyles 
    {
        get
        {
            if (ProductSyles == null)
                return null;
            return ProductSyles.Where(s => s.Selected).ToArray();
        }
        set
        {
            if (value == null)
                return;
            ProductSyles = ProductSyles ?? new List<Styles>();
            ProductSyles.AddRange(value);
        }
    }
}

(For an explanation of why a surrogate array should be used in preference to a surrogate List<Styles>, see here.)

Community
  • 1
  • 1
dbc
  • 104,963
  • 20
  • 228
  • 340