Introduction

In this tip, I will show you a trick: how you can hide a string-type property in the serialized XML if it is empty. Empty but not null!

Background

Normally, if you use EmitDefaultValue = false on a string property, DataContractSerializer will ignore this property if it has its default value. String has the default value = null. An empty string will be serialized like e.g. <Title></Title>.

You can save a huge amount of characters, if these empty properties will be simply ignored. If in your application, it has no special meaning, if a string property is null or is empty, you can use this trick to hide empty string values.

How to do it

We make a private property, which will be used only for the transfer.
  1. /// <summary>
  2. /// This property will be used only for transfer
  3. /// </summary>
  4. [DataMember(EmitDefaultValue = false, Name = "Title")]
  5. private string TitleTransfer { get; set; }
It is private, but for the DataContractSerializer it is no problem. The original property will be decorated with IgnoreDataMember, so it will not be transported.
  1. /// <summary>
  2. /// Title of the person.
  3. /// It can be empty.
  4. /// </summary>
  5. [IgnoreDataMember]
  6. public string Title
  7. {
  8. get { return this.TitleTransfer ?? string.Empty; }
  9. set
  10. {
  11. this.TitleTransfer = String.IsNullOrEmpty(value) ? null : value;
  12. }
  13. }

In the setter of the original property, I set the transfer-property to null, if the value would be empty. So the transfer-property will never be empty but null.

Test it!

  1. var p1 = new Person() { Title = "Prof.", ForeName = "Albert", LastName = "Einstein" };
So a Person with Title will be serialized as usual.
  1. <Person xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="...">
  2. <ForeName>Albert</ForeName>
  3. <LastName>Einstein</LastName>
  4. <Title>Prof.</Title>
  5. </Person>
But a Person without Title (empty)...
  1. var p2 = new Person() { Title = string.Empty, ForeName = "Laszlo", LastName = "Vörös" };
... will be serialized like this:
  1. <Person xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="...">
  2. <ForeName>Laszlo</ForeName>
  3. <LastName>Vörös</LastName>
  4. </Person>