no decription about ShouldSerialize* pattern use in XmlSerializer
- Dominant language
- No language data
- Stars
- 4.8k
- Forks
- 6.1k
- Avg merge
- 15h 21m
- Merged PRs (30d)
- 370
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() };
serializer.Serialize(Console.Out, objEmpty);
Console.WriteLine();
// Example 3: filled array
var objWithValues = new MyClass { Names = new[] { "Jeff" } };
serializer.Serialize(Console.Out, objWithValues);
}
}
```
---
#### Document Details
⚠ *Do not edit this section. It is required for learn.microsoft.com ➟ GitHub issue linking.*
* ID: a9d20cd7-81d9-cf19-c9ac-f69f09e420e8
* Version Independent ID: a71be414-9ed7-3644-0a88-f137db247a73
* Platform ID: 38917e73-1c81-14cc-d30a-caabed2c5873
* Content: [XML and SOAP Serialization - .NET](https://learn.microsoft.com/en-us/dotnet/standard/serialization/xml-and-soap-serialization)
* Content Source: [docs/standard/serialization/xml-and-soap-serialization.md](https://github.com/dotnet/docs/blob/main/docs/standard/serialization/xml-and-soap-serialization.md)
* Service: **dotnet-fundamentals**
* GitHub Login: @gewarren
* Microsoft Alias: **gewarren**
Contributor guide
Assessment
This issue has not been assessed yet.