Export (0) Print
Expand All

NetDataContractSerializer Class

Serializes and deserializes an instance of a type into XML stream or document using the supplied .NET Framework types. This class cannot be inherited.

System.Object
  System.Runtime.Serialization.XmlObjectSerializer
    System.Runtime.Serialization.NetDataContractSerializer

Namespace:  System.Runtime.Serialization
Assembly:  System.Runtime.Serialization (in System.Runtime.Serialization.dll)

'Declaration
Public NotInheritable Class NetDataContractSerializer _
	Inherits XmlObjectSerializer _
	Implements IFormatter

The NetDataContractSerializer type exposes the following members.

  NameDescription
Public methodNetDataContractSerializerInitializes a new instance of the NetDataContractSerializer class.
Public methodNetDataContractSerializer(StreamingContext)Initializes a new instance of the NetDataContractSerializer class with the supplied streaming context data.
Public methodNetDataContractSerializer(String, String)Initializes a new instance of the NetDataContractSerializer class with the supplied XML root element and namespace.
Public methodNetDataContractSerializer(XmlDictionaryString, XmlDictionaryString)Initializes a new instance of the NetDataContractSerializer class with two parameters of type XmlDictionaryString that contain the root element and namespace used to specify the content.
Public methodNetDataContractSerializer(StreamingContext, Int32, Boolean, FormatterAssemblyStyle, ISurrogateSelector)Initializes a new instance of the NetDataContractSerializer class with the supplied context data; in addition, specifies the maximum number of items in the object to be serialized, and parameters to specify whether extra data is ignored, the assembly loading method, and a surrogate selector.
Public methodNetDataContractSerializer(String, String, StreamingContext, Int32, Boolean, FormatterAssemblyStyle, ISurrogateSelector)Initializes a new instance of the NetDataContractSerializer class with the supplied context data and root name and namespace; in addition, specifies the maximum number of items in the object to be serialized, and parameters to specify whether extra data is ignored, the assembly loading method, and a surrogate selector.
Public methodNetDataContractSerializer(XmlDictionaryString, XmlDictionaryString, StreamingContext, Int32, Boolean, FormatterAssemblyStyle, ISurrogateSelector)Initializes a new instance of the NetDataContractSerializer class with the supplied context data, and root name and namespace (as XmlDictionaryString parameters); in addition, specifies the maximum number of items in the object to be serialized, and parameters to specify whether extra data found is ignored, assembly loading method, and a surrogate selector.
Top

  NameDescription
Public propertyAssemblyFormatGets a value that specifies a method for locating and loading assemblies.
Public propertyBinderGets or sets an object that controls class loading.
Public propertyContextGets or sets the object that enables the passing of context data that is useful while serializing or deserializing.
Public propertyIgnoreExtensionDataObjectGets a value that specifies whether data supplied by an extension of the object is ignored.
Public propertyMaxItemsInObjectGraphGets the maximum number of items allowed in the object to be serialized.
Public propertySurrogateSelectorGets or sets an object that assists the formatter when selecting a surrogate for serialization.
Top

  NameDescription
Public methodDeserializeDeserializes an XML document or stream into an object.
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodIsStartObject(XmlDictionaryReader)Determines whether the XmlDictionaryReader is positioned on an object that can be deserialized using the specified reader. (Overrides XmlObjectSerializer.IsStartObject(XmlDictionaryReader).)
Public methodIsStartObject(XmlReader)Determines whether the XmlReader is positioned on an object that can be deserialized using the specified reader. (Overrides XmlObjectSerializer.IsStartObject(XmlReader).)
Public methodReadObject(Stream)Reads the XML stream or document with a Stream and returns the deserialized object. (Inherited from XmlObjectSerializer.)
Public methodReadObject(XmlDictionaryReader)Reads the XML document or stream with an XmlDictionaryReader and returns the deserialized object. (Inherited from XmlObjectSerializer.)
Public methodReadObject(XmlReader)Reads the XML stream or document with an XmlDictionaryReader and returns the deserialized object. (Overrides XmlObjectSerializer.ReadObject(XmlReader).)
Public methodReadObject(XmlDictionaryReader, Boolean)Reads the XML stream or document with an XmlDictionaryReader and returns the deserialized object; also checks whether the object data conforms to the name and namespace used to create the serializer. (Overrides XmlObjectSerializer.ReadObject(XmlDictionaryReader, Boolean).)
Public methodReadObject(XmlReader, Boolean)Reads the XML stream or document with an XmlDictionaryReader and returns the deserialized object; also checks whether the object data conforms to the name and namespace used to create the serializer. (Overrides XmlObjectSerializer.ReadObject(XmlReader, Boolean).)
Public methodSerializeSerializes the specified object graph using the specified writer.
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Public methodWriteEndObject(XmlDictionaryWriter)Writes the closing XML element using an XmlDictionaryWriter. (Overrides XmlObjectSerializer.WriteEndObject(XmlDictionaryWriter).)
Public methodWriteEndObject(XmlWriter)Writes the closing XML element using an XmlWriter. (Overrides XmlObjectSerializer.WriteEndObject(XmlWriter).)
Public methodWriteObject(Stream, Object)Writes the complete content (start, content, and end) of the object to the XML document or stream with the specified Stream. (Inherited from XmlObjectSerializer.)
Public methodWriteObject(XmlDictionaryWriter, Object)Writes the complete content (start, content, and end) of the object to the XML document or stream with the specified XmlDictionaryWriter. (Inherited from XmlObjectSerializer.)
Public methodWriteObject(XmlWriter, Object)Writes the complete content (start, content, and end) of the object to the XML document or stream with the specified XmlWriter. (Overrides XmlObjectSerializer.WriteObject(XmlWriter, Object).)
Public methodWriteObjectContent(XmlDictionaryWriter, Object)Writes the XML content using an XmlDictionaryWriter. (Overrides XmlObjectSerializer.WriteObjectContent(XmlDictionaryWriter, Object).)
Public methodWriteObjectContent(XmlWriter, Object)Writes the XML content using an XmlWriter. (Overrides XmlObjectSerializer.WriteObjectContent(XmlWriter, Object).)
Public methodWriteStartObject(XmlDictionaryWriter, Object)Writes the opening XML element using an XmlDictionaryWriter. (Overrides XmlObjectSerializer.WriteStartObject(XmlDictionaryWriter, Object).)
Public methodWriteStartObject(XmlWriter, Object)Writes the opening XML element using an XmlWriter. (Overrides XmlObjectSerializer.WriteStartObject(XmlWriter, Object).)
Top

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 Serialization and Deserialization.

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)

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.

The following example code shows a type named Person that is serialized by the NetDataContractSerializer. The DataContractAttribute attribute is applied to the class, and the DataMemberAttribute is applied to members (including a private member) to instruct the NetDataContractSerializer what to serialize.

' You must apply a DataContractAttribute or SerializableAttribute 
' to a class to have it serialized by the NetDataContractSerializer.
<DataContract(Name := "Customer", [Namespace] := "http://www.contoso.com")>  _
Class Person
    Implements IExtensibleDataObject
    <DataMember()>  _
    Public FirstName As String
    <DataMember()>  _
    Public LastName As String
    <DataMember()>  _
    Public ID As Integer 


    Public Sub New(ByVal newfName As String, ByVal newLName As String, _
       ByVal newID As Integer) 
        FirstName = newfName
        LastName = newLName
        ID = newID

    End Sub  

    Private extensionData_Value As ExtensionDataObject


    Public Property ExtensionData() As ExtensionDataObject _
     Implements IExtensibleDataObject.ExtensionData
        Get 
            Return extensionData_Value
        End Get 
        Set
            extensionData_Value = value
        End Set 
    End Property 
End Class  


NotInheritable Public Class Test

    Private Sub New() 

    End Sub 

    Public Shared Sub Main() 
        Try
            WriteObject("NetDataContractSerializerExample.xml")
            ReadObject("NetDataContractSerializerExample.xml")

        Catch serExc As SerializationException
            Console.WriteLine("Serialization Failed")
            Console.WriteLine(serExc.Message)
        Catch exc As Exception
            Console.WriteLine("The serialization operation failed: {0} StackTrace: {1}", exc.Message, exc.StackTrace)

        Finally
            Console.WriteLine("Press <Enter> to exit....")
            Console.ReadLine()
        End Try 

    End Sub  


    Public Shared Sub WriteObject(ByVal fileName As String) 
        Console.WriteLine("Creating a Person object and serializing it.")
        Dim p1 As New Person("Zighetti", "Barbara", 101)
        Dim fs As New FileStream(fileName, FileMode.Create)
        Dim writer As XmlDictionaryWriter = XmlDictionaryWriter.CreateTextWriter(fs)
        Dim ser As New System.Runtime.Serialization.NetDataContractSerializer()

        ser.WriteObject(writer, p1)
        writer.Close()

    End Sub      

    Public Shared Sub ReadObject(ByVal fileName As String) 
        Console.WriteLine("Deserializing an instance of the object.")
        Dim fs As New FileStream(fileName, FileMode.Open)
        Dim reader As XmlDictionaryReader = _
           XmlDictionaryReader.CreateTextReader(fs, New XmlDictionaryReaderQuotas())
        Dim ser As New System.Runtime.Serialization.NetDataContractSerializer()

        ' Deserialize the data and read it from the instance. 
        Dim deserializedPerson As Person = CType(ser.ReadObject(reader, True), Person)
        fs.Close()
        Console.WriteLine(String.Format("{0} {1}, ID: {2}", deserializedPerson.FirstName, deserializedPerson.LastName, deserializedPerson.ID))

    End Sub  
End Class

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2014 Microsoft