MrFox
MrFox

Reputation: 3253

How to tell C# to omit creation of attributes that are default during serialization?

I have a class that is serialized to a XML file. There are several properties that are rarely used but always created. If I delete them within the XML the deserialization still works, because they have the default value.

These unnecessary (bool) attributes make the XML harder to read.

Can I somehow tell C# to omit elements or attributes that still have default value?

Upvotes: 5

Views: 2199

Answers (3)

Marc Gravell
Marc Gravell

Reputation: 1062650

Rowland has the answer for simple values. For more complex scenarios, you can add a method called public bool ShouldSerializeFoo() (for property Foo) - it it returns false, it won't get serialized.

Upvotes: 6

Ben
Ben

Reputation: 3912

Use the XMLIgnore() Attribute to mark a property to be ingnored in Serialization / Deserialization.

Upvotes: -1

Rowland Shaw
Rowland Shaw

Reputation: 38130

Specify the DefaultValueAttribute, and if the value matches, it won't be output.

Upvotes: 12

Related Questions