Search code examples
c#xmlxml-serializationixmlserializable

Xml Serialization Dynamic Ignore


I am trying to generate an xml document in a specific format. I would like to skip serializing a property depending on a value of the property.

public class Parent
{
    public Parent()
    {
        myChild = new Child();
        myChild2 = new Child() { Value = "Value" };
    }
    public Child myChild { get; set; }
    public Child myChild2 { get; set; }
}

public class Child
{
    private bool _set;
    public bool Set { get { return _set; } }

    private string _value = "default";
    [System.Xml.Serialization.XmlText()]
    public string Value
    {
        get { return _value; }
        set { _value = value; _set = true; }
    }
}

System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(Parent));
x.Serialize(Console.Out, new Parent());

If Set is false, I want the entire property to not be serialized, my resulting xml should be

<Parent>
   <myChild2>default</myChild2>
</Parent>

Instead of

<Parent>
   <myChild/>
   <myChild2>default</myChild2>
</Parent>

Is there some way I can do this cleanly with IXmlSerializable or anything else?

Thanks!


Solution

  • There is a ShouldSerialize* pattern (introduced by TypeDescriptor, but recognised by a few other areas of code, such as XmlSerializer):

    public bool ShouldSerializemyChild() {
         return myChild != null && myChild.Set;
    }
    

    That should sort it.

    A simpler option, though, is to assign it null.