views:

336

answers:

1

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.

  1. Custom XmlTextWriter that buffers itself and drops empty elements
  2. Before an object is serialized, cycle through the prop, setting Empty to Nothing, Count-0 to Nothing
  3. XSLT that drops empty elements
  4. 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?

A: 

The answer is that the Data Contract Serializer is not meant to give you so much control over the format of the XML. That's not what it's about. If you need this much control, then you need to use the XML Serializer, and you may need to implement IXmlSerializable.

Alternatively, you could revisit your reasons for not wanting to serialize these "empty" objects. You may find that it's not worth your time.

John Saunders