Monday, 31 December 2018

XML Media-Type Formatter

XML formatting is provided by the XmlMediaTypeFormatter class. By default, XmlMediaTypeFormatter uses the DataContractSerializer class to perform serialization.

If you prefer, you can configure the XmlMediaTypeFormatter to use the XmlSerializer instead of the DataContractSerializer. To do so, set the UseXmlSerializer property to true:

var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
xml.UseXmlSerializer = true;

The XmlSerializer class supports a narrower set of types than DataContractSerializer, but gives more control over the resulting XML. Consider using XmlSerializer if you need to match an existing XML schema.

XML Serialization

By default, the DataContractSerializer behaves as follows:
·       All public read/write properties and fields are serialized. To omit a property or field, decorate it with the IgnoreDataMember attribute.
·       Private and protected members are not serialized.
·       Read-only properties are not serialized. (However, the contents of a read-only collection property are serialized.)
·       Class and member names are written in the XML exactly as they appear in the class declaration.
·       A default XML namespace is used.

If you need more control over the serialization, you can decorate the class with the DataContract attribute. When this attribute is present, the class is serialized as follows:

·       "Opt in" approach: Properties and fields are not serialized by default. To serialize a property or field, decorate it with the DataMember attribute.
·       To serialize a private or protected member, decorate it with the DataMember attribute.
·       Read-only properties are not serialized.
·       To change how the class name appears in the XML, set the Name parameter in the DataContract attribute.
·       To change how a member name appears in the XML, set the Name parameter in the DataMember attribute.

·       To change the XML namespace, set the Namespace parameter in the DataContract class.

No comments:

Post a Comment