Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# xml serialization

I'm serializing an object to xml in c# and I would like to serialize

public String Marker { get; set; }

into

<Marker></Marker>

when string Marker has no value.

Now I get

<Marker />

for Marker == string.Empty and no Marker node for null. How can I get this ?

like image 377
Jonah Avatar asked Mar 21 '26 07:03

Jonah


1 Answers

You can easily suppress the <Marker> element if the Marker property is null. Just add a ShouldSerializeMarker() method:

public bool ShouldSerializeMarker()
{
    return Marker != null;
}

It will be called automatically by XmlSerializer to decide whether or not to include the element in the output.

As for using the expanded form of the <Marker> element when the string is empty, there's no easy way to do it (you could probably write your own XmlWriter, but it would be a pain). But anyway it doesn't make sense, because <Marker /> and <Marker></Marker> have exactly the same meaning.

like image 57
Thomas Levesque Avatar answered Mar 23 '26 21:03

Thomas Levesque