Is there a way to make DataContractSerializer output cleaner XML?

This is happening because you must have marked your types (e.g. AgentNotification) with [Serializable]. When DataContractSerializer encounters a type marked with [Serializable] but no explicit [DataContract], it generates a default contract for the type that matches how BinaryFormatter serializes a class, which is to serialize all member variables of a class — even variables marked as private — by name. For auto-implemented properties, this means the secret backing fields get serialized by name; their names are the peculiar element names you are seeing.

The easiest way to solve this is to remove the [Serializable] attribute from your classes. You almost certainly don’t need it unless you are actually using BinaryFormatter or SoapFormatter. Having done so, DataContractSerializer will now serialize your public properties and fields by name, rather than public and private fields by name.

Leave a Comment