Is there a way to have XmlSerializer ignore all members by default, unless I say otherwise?
I have a base class and several derived classes with lots of members, but most I do not want to be serialized. Only a select few are acceptable for serialization.
No, you cannot do this.
The XmlSerializer is using a “opt-out” process – it will serialize everything (all public properties) unless you explicitly opt-out by using the
[XmlIgnore]attribute. There’s no way of changing this behavior.The .NET 3.5 DataContractSerializer on the other hand is taking the other approach – opt-in. It will not serialize anything, unless you specifically tell it to, by decorating your members with
[DataMember].So maybe the DataContract serializer would work for you? It was a few more advantages (doesn’t require a parameter-less constructor, can serialize internal and private properties, too, and it can also serialize fields instead of properties, if needed), and it’s tuned for speed. There’s some downsides, too – it doesn’t support attributes in XML nodes – so you’ll have to pick based on your requirements.
There’s a good comparison of the two by Dan Rigsby – check it out!
Marc