views:

141

answers:

1

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 ?

A: 

Write your own xml serializer. You could use the interface IXmlSerializable or you could just write your own ToXml method which outputs a string. There are many ways to do it but writing your own will give you what you want.

Joshua Cauble
You're right at some point. I added this : public void WriteXml(XmlWriter writer){ if (!string.IsNullOrEmpty(Label)) { writer.WriteElementString("id", Id); writer.WriteElementString("label", Label); }}though it works for my collection, it also means that a single Item that has no label won't serialize anymore. Thus using the IXmlSerializable has a global impact, which I don't want.
hoang
Moreover, the collection render an empty <item/> node :'(
hoang