Xml serialization - Hide null values

.net, c#, xml-serialization

Solution

You can create a function with the pattern `ShouldSerialize{PropertyName}` which tells the XmlSerializer if it should serialize the member or not.

For example, if your class property is called `MyNullableInt` you could have

public bool ShouldSerializeMyNullableInt() 
{
  return MyNullableInt.HasValue;
}

Here is a full sample

public class Person
{
  public string Name {get;set;}
  public int? Age {get;set;}
  public bool ShouldSerializeAge()
  {
    return Age.HasValue;
  }
}

Serialized with the following code

Person thePerson = new Person(){Name="Chris"};
XmlSerializer xs = new XmlSerializer(typeof(Person));
StringWriter sw = new StringWriter();
xs.Serialize(sw, thePerson);

Results in the followng XML - Notice there is no Age

<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>Chris</Name>
</Person>

Problem

When using a standard .NET Xml Serializer, is there any way I can hide all null values? The below is an example of the output of my class. I don't want to output the nullable integers if they are set to null. Current Xml output: ``` <?xml version="1.0" encoding="utf-8"?> <myClass> <myNullableInt p2:nil="true" xmlns:p2="http://www.w3.org/2001/XMLSchema-instance" /> <myOtherInt>-1</myOtherInt> </myClass> ``` What I want: ``` <?xml version="1.0" encoding="utf-8"?> <myClass> <myOtherInt>-1</myOtherInt> </myClass> ```

Original source