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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With