-
Notifications
You must be signed in to change notification settings - Fork 6.1k
Open
Labels
⌚ Not TriagedNot triagedNot triaged
Description
Describe the issue or suggestion
The XmlSerializer allows that class to serialize specifiy a ShouldSerialize* method, to prevent serialization in certain cases, i.e. array is empty. This is somehow documented for winforms but not for XmlSerializer.
Important difference to Winforms implementation is that the method has to be public!
I am right now not sure if there are Reset and *Specified working.
Here a tested example:
using System.Xml.Serialization;
public class MyClass
{
[XmlArray("Names")]
[XmlArrayItem("Name")]
public string[] Names { get; set; }
// Control whether the array is serialized
public bool ShouldSerializeNames()
{
return Names != null && Names.Length > 0;
}
}
class Program
{
static void Main()
{
var serializer = new XmlSerializer(typeof(MyClass));
// Example 1: null array
var objNull = new MyClass { Names = null };
serializer.Serialize(Console.Out, objNull);
Console.WriteLine();
// Example 2: Empty array
var objEmpty = new MyClass { Names = Array.Empty<string>() };
serializer.Serialize(Console.Out, objEmpty);
Console.WriteLine();
// Example 3: filled array
var objWithValues = new MyClass { Names = new[] { "Jeff" } };
serializer.Serialize(Console.Out, objWithValues);
}
}
Metadata
Metadata
Assignees
Labels
⌚ Not TriagedNot triagedNot triaged