The NetDataContractSerializer differs from the DataContractSerializer in one important way: the NetDataContractSerializer includes CLR type information in the serialized XML, whereas the DataContractSerializer does not. Therefore, the NetDataContractSerializer can be used only if both the serializing and deserializing ends share the same CLR types.
The serializer can serialize types to which either the DataContractAttribute or SerializableAttribute attribute has been applied. It also serializes types that implement ISerializable.
For more information about serialization, see Using Stand-alone Serialization.
Incompatibility with XElement
The XElement class is used to write XML. However, the NetDataContractSerializer cannot serialize an instance of the type. The following code, therefore, fails with the exception: "Root type 'System.Xml.Linq.XElement' is not supported at the top level by NetDataContractSerializer since it is IXmlSerializable with IsAny=true and must write all its contents including the root element."
Dim fs As New FileStream("mystuff.xml", FileMode.Create, FileAccess.ReadWrite)
Dim myElement As New XElement("Parent", New XElement("child1", "form"), _
New XElement("child2", "base"), _
New XElement("child3", "formbase") _
)
Dim ser As New System.Runtime.Serialization. _
NetDataContractSerializer()
ser.WriteObject(fs, myElement)
FileStream fs = new FileStream("mystuff.xml", FileMode.Create, FileAccess.ReadWrite);
XElement myElement = new XElement("Parent", new XElement("child1", "form"),
new XElement("child2", "base"),
new XElement("child3", "formbase")
);
NetDataContractSerializer dcs = new NetDataContractSerializer();
dcs.WriteObject(fs, myElement);
However, if an XElement is used as the type of a field or property of a class, the data contained by the field or property is serialized. This is because as a member of a class, the data is not the top level of the class.