XmlSerializer, "Specified" Suffix, and IReflect

I found that if the serializable field / property has a corresponding field of type Boolean having the name of the field / property with the suffix "Specified", XmlSerializer conditionally excludes this field / property from the serialization process. Nice!

So, I want to avoid defining these fields and add them dynamically at runtime ...

Reading this , I found an interesting IReflect interface that I can use to "emulate" dynamic fields that XmlSerializer instances use to exclude specific fields.

Will this work?

+6
reflection c # xml-serialization
source share
2 answers

If you want to take control of xml serialization, you have two options. The first (which may not be acceptable here) is to use attributes in the System.Xml.Serialization namespace to exclude properties. If you really need to determine what is being serialized at runtime, this might not be the best course of action.

See Attributes That Control XML Serialization

Another way to do this is to implement the IXmlSerializable interface in your class and implement the ReadXml and WriteXml methods. This allows you to precisely control how your xml looks. See this question for more information:

custom XML serialization

However, as mentioned here Mixing custom and basic serialization? after implementing IXmlSerializable, you are responsible for all the serialization logic for your type.

+2
source share

I will continue Martin Peck's answer. You can avoid serializing fields / properties using the "Specified" suffix. You must define the "* Specified" properties in your class and apply [XmlIgnoreAttribute()] .

Here is an example:

 [System.SerializableAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://yournamespace.com")] public partial class YourObject { private long sessionTimeoutInSecondsField; private bool sessionTimeoutInSecondsFieldSpecified; public long sessionTimeoutInSeconds { get { return this.sessionTimeoutInSecondsField; } set { this.sessionTimeoutInSecondsField = value; } } [System.Xml.Serialization.XmlIgnoreAttribute()] public bool sessionTimeoutInSecondsSpecified { get { return this.sessionTimeoutInSecondsFieldSpecified; } set { this.sessionTimeoutInSecondsFieldSpecified = value; } } } 
+2
source share

All Articles