Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude null properties when using XmlSerializer

I'm serializing a class like this

public MyClass {     public int? a { get; set; }     public int? b { get; set; }     public int? c { get; set; } } 

All of the types are nullable because I want minimal data stored when serializing an object of this type. However, when it is serialized with only "a" populated, I get the following xml

<MyClass ...>     <a>3</a>     <b xsi:nil="true" />     <c xsi:nil="true" /> </MyClass> 

How do I set this up to only get xml for the non null properties? The desired output would be

<MyClass ...>     <a>3</a> </MyClass> 

I want to exclude these null values because there will be several properties and this is getting stored in a database (yeah, thats not my call) so I want to keep the unused data minimal.

like image 719
Allen Rice Avatar asked Oct 07 '09 18:10

Allen Rice


People also ask

What is XML ignore attribute?

Remarks. The XmlIgnoreAttribute belongs to a family of attributes that controls how the XmlSerializer serializes or deserializes an object. If you apply the XmlIgnoreAttribute to any member of a class, the XmlSerializer ignores the member when serializing or deserializing an instance of the class.

Is XmlSerializer thread safe?

Since XmlSerializer is one of the few thread safe classes in the framework you really only need a single instance of each serializer even in a multithreaded application. The only thing left for you to do, is to devise a way to always retrieve the same instance.

How does the XmlSerializer work C#?

The XmlSerializer creates C# (. cs) files and compiles them into . dll files in the directory named by the TEMP environment variable; serialization occurs with those DLLs. These serialization assemblies can be generated in advance and signed by using the SGen.exe tool.

Why do we use XmlSerializer class?

XmlSerializer enables you to control how objects are encoded into XML. The XmlSerializer enables you to control how objects are encoded into XML, it has a number of constructors.


1 Answers

You ignore specific elements with specification

public MyClass {     public int? a { get; set; }      [System.Xml.Serialization.XmlIgnore]     public bool aSpecified { get { return this.a != null; } }      public int? b { get; set; }     [System.Xml.Serialization.XmlIgnore]     public bool bSpecified { get { return this.b != null; } }      public int? c { get; set; }     [System.Xml.Serialization.XmlIgnore]     public bool cSpecified { get { return this.c != null; } } } 

The {field}Specified properties will tell the serializer if it should serialize the corresponding fields or not by returning true/false.

like image 159
Allen Rice Avatar answered Sep 16 '22 11:09

Allen Rice