C# XML Serialization: Seralizizing Nullable Value Types (Want to Suppress "null" Values Without Decorators/Attributes/ShouldSerialize)

220 views Asked by At

I'm working with code in C# trying to serialize an object to XML. I cannot add XML attributes or extra properties (e.g. bool ShouldSerializeFoo) to this object. Nor can I add any [Xml*] attributes to properties. I can only control the XML Serializer.

Some of the properties are nullable types (int? et al), and I would like them to not be serialized if they are null (i.e. foo.HasValue is false).

Is there a way to instruct the XML serializer in C# to skip over null properties of nullable value types? If not, is there a way to hook into ShouldSerialize() for every property so I can inject custom logic into it? (I can manually check if the value is a nullable type and do HasValue checking myself).

Given this C# class:

public class SomeObject
{
    public int? Foo { get; set; }
    public string? Bar { get; set; }
}

If I set Foo to null and Bar to "Something", I'd like the XML output to be:

<SomeObject>
    <Bar>Something</Bar>
</SomeObject>

I am using something like this to invoke the serializer currently:

using System.Xml;
using System.Xml.Serialization;

// Class code omitted

public string CreateXML(SomeObject objToSerialize)
{
    XmlSerializer xmlSerializer = new(objToSerialize.GetType());
    using StringWriter stringWriter = new();
    using XmlWriter xmlWriter = XmlWriter.Create(stringWriter, new() { OmitXmlDeclaration = true });
    xmlSerializer.Serialize(xmlWriter, objToSerialize, new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }));
    return stringWriter.ToString();
}

If what I want is impossible, I will resort to manually editing the serialized XML after the fact in order to remove them (regular expressions to find and replace 'nil' elements with an empty string), but I would rather the serializer just skip those values in the first place.

0

There are 0 answers