Davita
Davita

Reputation: 9144

How to include null properties during xml serialization

Currently, the code below omits null properties during serialization. I want null valued properties in the output xml as empty elements. I searched the web but didn't find anything useful. Any help would be appreciated.

        var serializer = new XmlSerializer(application.GetType());
        var ms = new MemoryStream();
        var writer = new StreamWriter(ms);
        serializer.Serialize(writer, application);
        return ms;

Sorry, I forgot to mention that I want to avoid attribute decoration.

Upvotes: 14

Views: 38314

Answers (3)

Anand
Anand

Reputation: 14955

You can use also use the following code. The pattern is ShouldSerialize{PropertyName}

public class PersonWithNullProperties
{
    public string Name { get; set; }
    public int? Age { get; set; }
    public bool ShouldSerializeAge()
    {
        return true;
    }
}

  PersonWithNullProperties nullPerson = new PersonWithNullProperties() { Name = "ABCD" };
  XmlSerializer xs = new XmlSerializer(typeof(nullPerson));
  StringWriter sw = new StringWriter();
  xs.Serialize(sw, nullPerson);

XML

<?xml version="1.0" encoding="utf-16"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://
www.w3.org/2001/XMLSchema">
  <Name>ABCD</Name>
  <Age xsi:nil="true" />
</Person>

Upvotes: 1

Emanuele Greco
Emanuele Greco

Reputation: 12731

Can you control the items that have to be serialized?
Using

[XmlElement(IsNullable = true)]
public string Prop { get; set; }

you can represent it as <Prop xsi:nil="true" />

Upvotes: 28

Related Questions