I'm working on getting some objects serialized through an mvc site and returning things via xml, json, etc and I'm looking for the best way to not send the empty elements.
In a perfect world, simply attaching EmitDefaultValue:=False to DataMembers in a DataContract would suffice, but in some situations, it just doesn't fly.
A String default is Nothing, but I don't want to serialize them if they are Nothing or String.Empty. Same goes for lists and collections. I don't want them to serialize if they're Nothing or if they're empty with a count of 0.
There seems to be a few not so pretty options.
- Custom
XmlTextWriter
that buffers itself and drops empty elements - Before an object is serialized, cycle through the prop, setting Empty to Nothing, Count-0 to Nothing
- XSLT that drops empty elements
- Regex the output string on the way out
All of these seem some what evil, 1 being the least evil but the leave trivial to do. Is there some other tricks out there?