Dynamic Ignore Xml Serialization

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!

+6
source share
4 answers

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

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

That should sort it out.

A simpler option is to set it to null.

+6
source

If "mychild" is defined by an array, I think it can succeed ...

 public class Parent { public Parent() { myChild = new Child[]{ new Child(){Value = "Value"}}; //myChild2 = new Child() { Value = "Value" }; } public Child[] myChild { get; set; } //public Child myChild2 { get; set; } } 
0
source

I think this might work, although you need to override the Equals method

 [DefaultValue(new Child())] public Child myChild{ get; set; } 
0
source

Just wrote this code for fun and maybe found out something in the process. It should set any property to null if this property contains the Set method, which returns bool, and its current value is false. By setting the value to false, it should solve the serializer problem. Any suggestions:

 public static void RemoveUnsetObjects(object currentObject) { var type = currentObject.GetType(); if (currentObject is IEnumerable) { IEnumerable list = (currentObject as IEnumerable); foreach (object o in list) { RemoveUnsetObjects(o); } } else { foreach (var p in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)) { var propertyValue = p.GetValue(currentObject, null); if (propertyValue == null) continue; var setPropInfo = p.PropertyType.GetProperty("Set", typeof(bool)); if (setPropInfo != null) { var isSet = (bool)setPropInfo.GetValue(propertyValue, null); if (!isSet) { p.SetValue(currentObject, null, null); } } else { RemoveUnsetObjects(propertyValue); } } } } 
0
source

Source: https://habr.com/ru/post/890837/


All Articles