Skip to content

Instantly share code, notes, and snippets.

@hallojoe
Created September 23, 2025 13:31
Show Gist options
  • Select an option

  • Save hallojoe/4cf68bdeaaffc986c4ceed3d15c984ea to your computer and use it in GitHub Desktop.

Select an option

Save hallojoe/4cf68bdeaaffc986c4ceed3d15c984ea to your computer and use it in GitHub Desktop.

XML Serialization Control in C#

When working with System.Xml.Serialization.XmlSerializer, you can control how POCO properties are serialized using naming conventions and attributes.


1. The Specified Suffix

  • Pattern: <PropertyName>Specified
  • Type: bool
  • Effect: Controls whether <PropertyName> is serialized at all.

Example

public int Priority { get; set; }
public bool PrioritySpecified { get; set; }
  • If PrioritySpecified = false, the <Priority> element is omitted.

2. The ShouldSerialize<PropertyName> Method

  • Pattern: public bool ShouldSerialize<PropertyName>()
  • Effect: Alternative to *Specified property. If the method returns false, the property is not serialized.

Example

public int Priority { get; set; }
public bool ShouldSerializePriority() => Priority > 0;

3. The Reset<PropertyName> Method

  • Pattern: public void Reset<PropertyName>()
  • Effect: Used with XmlSerializer and some designers. Indicates how to reset a property to its default.

(Not directly about omitting XML, but sometimes paired with ShouldSerialize<PropertyName>()).


4. Attributes That Change Serialization

Besides naming conventions, attributes give fine-grained control:

  • [XmlIgnore] → Prevents serialization of a property or field.
  • [XmlAttribute] → Serializes as an attribute instead of an element.
  • [XmlElement(IsNullable = true)] → Controls xsi:nil output.
  • [DefaultValue(...)] (from System.ComponentModel) → If property equals default, serializer may skip it.

✅ Summary of Special Naming Conventions

  1. *Specified boolean property → Controls element inclusion.
  2. ShouldSerialize<PropertyName>() method → Controls serialization via code logic.
  3. Reset<PropertyName>() method → Used for resetting to defaults.

Attributes provide additional control beyond these conventions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment