I was going through WCF Fundamentals, Can anybody tells that under which scenarios should we use DataContractSerializer and XmlSerializer?
Asked
Active
Viewed 1.6k times
2 Answers
13
DataContractSerializer
- Is meant to be used for serialization/deserialization of class in WCF service to and from either JSON or XML.
- serializes properties and fields.
- Is faster than XmlSerializer
- Doesn't control how xml is generated. Should not be used when full control on generated XML structure is required
XMLSerializer
- XmlSerializer is only for XML serialization
- Supports full control over the XML structure
- Serializes only public properties

Joseph Daigle
- 47,650
- 10
- 49
- 73

Ronak Patel
- 2,570
- 17
- 20
-
I can't find anything saying DataContractSerializer can do JSON. This is what the DataContractJsonSerializer is for. From MSDN - DataContractSerializer: Serializes and deserializes an instance of a type into an XML stream or document using a supplied data contract. This class cannot be inherited. – NielW May 05 '19 at 00:38
-
Try creating a demo in WCF and use the serializer – Ronak Patel May 09 '19 at 07:25
-
Another important difference: with XmlSerializer, you must have a parameterless constructor. With DataContractSerializer, you do not need it. Even if you have one, it won't be used when deserializing. – sthiers Dec 18 '19 at 14:44
-
XmlSerializer "serializes only public properties". This is not true. It will also serialize public data members that are not properties. – H2ONaCl Mar 01 '21 at 03:47
12
DataContractSerializer is better performance over Xmlserializer. This is because DataContratSerializer explicitly shows the which fields or properties are serialized into XML.
DataContractSerializer can able to serialize types that implements Idictionary whereas XML serializer not.
DataContractSerializer serializes all members which are marked with [DataMember] attribute even if member is marked private. XML serializer serialize only public members.
These are some important difference.

Vikas Gupta
- 188
- 1
- 7