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?


public class Test
  public string value {set; get; }

  public string key {set; get; }

When value is null, i get
  <Test key="blah">


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

XmlElement( IsNullable = true )

Method 2

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

Method 3

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.

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x