14

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.

Davita
  • 8,928
  • 14
  • 67
  • 119
  • 2
    A couple of dupes: [XML Serialization and null value - C#](http://stackoverflow.com/questions/711723/xml-serialization-and-null-value-c-sharp) and [XmlSerializer. Keep null string properties?](http://stackoverflow.com/questions/10733731/xmlserializer-keep-null-string-properties) – Darin Dimitrov Aug 29 '13 at 15:34
  • Why do you want to do so? It doesn't make sense for me – Sriram Sakthivel Aug 29 '13 at 15:34
  • 2
    Careful, empty elements are _not equatable_ to non-existing/null elements. For example, XML serializing a `string` property, an empty element will produce an empty string `""` (`String.Empty`) for that property, where as a non-existing (or an element with `xsi:nil="true"` attribute) element will produce a `null` reference value for that same property. – Chris Sinclair Aug 29 '13 at 16:08

3 Answers3

27

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" />

Emanuele Greco
  • 12,551
  • 7
  • 51
  • 70
1

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>
Anand
  • 14,545
  • 8
  • 32
  • 44
0

Set the XmlElementAttribute.IsNullable property:

https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlelementattribute.isnullable(v=vs.110).aspx

Tim Abell
  • 11,186
  • 8
  • 79
  • 110
user2722002
  • 65
  • 1
  • 6