21

I have an object that I serialize to XML. If one of the properties in the object is null, then native serialization ignores to add this as the attribute. Is this normal behavior, if so, is there a way I can override it?

ex:

public class Test
{
  [XmlAttribute]
  public string value {set; get; }

  [XmlAttribute]
  public string key {set; get; }
}

When value is null, i get

<Root>
  <Test key="blah">
</Root>
DotnetDude
  • 11,617
  • 35
  • 100
  • 158

3 Answers3

34

XmlElement( IsNullable = true )

Sunny Milenov
  • 21,990
  • 6
  • 80
  • 106
  • I like this and it can be applied to an individual element. Is there any way to specify that for a given class with a huge number of fields (let's say 1,000) that this is the default for all fields without having to touch each and every field? – froggythefrog Aug 25 '13 at 23:37
  • BTW, it's not that I have so many fields in a single class. It's actually that I have tons of classes for a WCF service and want to create REST messages by serializing them. I want the service to include all fields, regardless of their value or lack thereof. – froggythefrog Aug 25 '13 at 23:39
  • 1
    This is a framework concern (your services == framework :) ). I.e. if you want all your services to behave the same way, don't change the data classes. Change the serializer used. You can hook into WCF, and replace the default serializer with your custome one. – Sunny Milenov Aug 27 '13 at 13:11
  • That sounds like what I will need to do, then. – froggythefrog Aug 28 '13 at 20:31
2

In case Sunny's answer just doesn't fits to you, you can customize the serialization process by implementing the IXmlSerializable interface

Jhonny D. Cano -Leftware-
  • 17,663
  • 14
  • 81
  • 103
1

For some background, take a look at the following ibm article Representations of null in XML Schema

Additionally check out the answer SO question Serialize a nullable int may be helpful in your efforts.

Community
  • 1
  • 1
Robert Paulson
  • 17,603
  • 5
  • 34
  • 53