I am trying to create an XML document in a specific format. I would like to skip serializing the property depending on the 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 false, I want the whole property not to be serialized, my resulting xml should be
<Parent> <myChild2>default</myChild2> </Parent>
Instead
<Parent> <myChild/> <myChild2>default</myChild2> </Parent>
Is there a way to do this using IXmlSerializable or something else?
Thanks!
source share