Skip to content

no decription about ShouldSerialize* pattern use in XmlSerializer #50596

@trivalik

Description

@trivalik

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

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions