Neomoon
Neomoon

Reputation: 181

Conditional XML serialization of list items

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

Upvotes: 2

Views: 788

Answers (1)

dbc
dbc

Reputation: 116785

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.)

Upvotes: 1

Related Questions