DotnetDude
DotnetDude

Reputation: 11817

XML Serialization and null value - C#

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>

Upvotes: 22

Views: 31380

Answers (3)

Robert Paulson
Robert Paulson

Reputation: 18081

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.

Upvotes: 1

Jhonny D. Cano -Leftware-
Jhonny D. Cano -Leftware-

Reputation: 18013

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

Upvotes: 2

Related Questions