Donnerstag, Mai 24, 2007
XML Serializer & Default Attribute Value
Old stuff: The .NET XMLSerializer is quite powerful, but not perfectly documented. Hmm.
I found for example the support for default attribute values *is* there and also more or less complete!
What we want: A class with an instance variable serialized to an attribute:
- Its Xml-Attribute representation shall only be written into the XML file when the actual value is different to the default one.
Solution: specify default with System.ComponentModel.DefaultValueAttribute - The value shall be restored when reading an xml file even if the value is not present.
Solution: add a default constructor and set the value yourself.
Untested Example:
[Serializable] [XmlRoot(ElementName="FILE")] public class Example { [XmlAttribute("filename")] [System.ComponentModel.DefaultValueAttribute(FileNameDefault)] public string FileName; public const string FileNameDefault = "default.xml"; public Example() { FileName = FileNameDefault; } }
Remember: to control what's happening you can also always take a look at the code generated by the XMLSerializer.