NetDataContractSerializer NetDataContractSerializer NetDataContractSerializer NetDataContractSerializer Class

Definición

Serializa y deserializa una instancia de un tipo en secuencia XML o en documento utilizando los tipos de .NET Framework proporcionados.Serializes and deserializes an instance of a type into XML stream or document using the supplied .NET Framework types. Esta clase no puede heredarse.This class cannot be inherited.

public ref class NetDataContractSerializer sealed : System::Runtime::Serialization::XmlObjectSerializer, System::Runtime::Serialization::IFormatter
public sealed class NetDataContractSerializer : System.Runtime.Serialization.XmlObjectSerializer, System.Runtime.Serialization.IFormatter
type NetDataContractSerializer = class
    inherit XmlObjectSerializer
    interface IFormatter
Public NotInheritable Class NetDataContractSerializer
Inherits XmlObjectSerializer
Implements IFormatter
Herencia
NetDataContractSerializerNetDataContractSerializerNetDataContractSerializerNetDataContractSerializer
Implementaciones

Ejemplos

El código de ejemplo siguiente muestra un tipo denominado Person que es serializado por NetDataContractSerializer.The following example code shows a type named Person that is serialized by the NetDataContractSerializer. El atributo DataContractAttribute se aplica a la clase y DataMemberAttribute se aplica a los miembros (incluso a un miembro privado) para indicar a NetDataContractSerializer qué debe serializar.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 : IExtensibleDataObject
{
    [DataMember()]
    public string FirstName;
    [DataMember]
    public string LastName;
    [DataMember()]
    public int ID;

    public Person(string newfName, string newLName, int newID)
    {
        FirstName = newfName;
        LastName = newLName;
        ID = newID;
    }

    private ExtensionDataObject extensionData_Value;

    public ExtensionDataObject ExtensionData
    {
        get
        {
            return extensionData_Value;
        }
        set
        {
            extensionData_Value = value;
        }
    }
}

public sealed class Test
{
    private Test() { }

    public static void Main()
    {
        try
        {
            WriteObject("NetDataContractSerializerExample.xml");
            ReadObject("NetDataContractSerializerExample.xml");
        }

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

        finally
        {
            Console.WriteLine("Press <Enter> to exit....");
            Console.ReadLine();
        }
    }

    public static void WriteObject(string fileName)
    {
        Console.WriteLine(
            "Creating a Person object and serializing it.");
        Person p1 = new Person("Zighetti", "Barbara", 101);
        FileStream fs = new FileStream(fileName, FileMode.Create);
        XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(fs);
        NetDataContractSerializer ser =
            new NetDataContractSerializer();
        ser.WriteObject(writer, p1);
        writer.Close();
    }

    public static void ReadObject(string fileName)
    {
        Console.WriteLine("Deserializing an instance of the object.");
        FileStream fs = new FileStream(fileName,
        FileMode.Open);
        XmlDictionaryReader reader =
            XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
        NetDataContractSerializer ser = new NetDataContractSerializer();

        // Deserialize the data and read it from the instance.
        Person deserializedPerson =
            (Person)ser.ReadObject(reader, true);
        fs.Close();
        Console.WriteLine(String.Format("{0} {1}, ID: {2}",
        deserializedPerson.FirstName, deserializedPerson.LastName,
        deserializedPerson.ID));
    }
}
' 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 

Comentarios

NetDataContractSerializer difiere de DataContractSerializer en un aspecto importante: NetDataContractSerializer incluye información de tipo CLR en el XML serializado, mientras que DataContractSerializer no lo hace.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. Por lo tanto, sólo se puede utilizar NetDataContractSerializer si los fines de serialización y de deserialización comparten los mismos tipos CLR.Therefore, the NetDataContractSerializer can be used only if both the serializing and deserializing ends share the same CLR types.

El serializador puede serializar los tipos a los que no se ha aplicado el atributo DataContractAttribute o SerializableAttribute.The serializer can serialize types to which either the DataContractAttribute or SerializableAttribute attribute has been applied. También serializa tipos que implementan ISerializable.It also serializes types that implement ISerializable.

Para obtener más información sobre la serialización, vea serialización ydeserialización.For more information about serialization, see Serialization and Deserialization.

Incompatibilidad con XElementIncompatibility with XElement

La clase XElement se utiliza para escribir XML.The XElement class is used to write XML. Sin embargo, NetDataContractSerializer no puede serializar ninguna instancia de ese tipo.However, the NetDataContractSerializer cannot serialize an instance of the type. Por lo tanto, el código siguiente produce un error con la excepción: "El tipo raíz ' System. Xml. Linq. XElement ' no se admite en el nivel superior por NetDataContractSerializer, ya que es IsAny IXmlSerializable con = true y debe escribir todo su contenido, incluido el elemento raíz."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."

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);
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)

Sin embargo, si XElement se utiliza como tipo de un campo o propiedad de una clase, se serializan los datos que contiene el campo o la propiedad.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. Esto sucede porque los datos, como miembro de una clase, no son el nivel superior de la clase.This is because as a member of a class, the data is not the top level of the class.

Constructores

NetDataContractSerializer() NetDataContractSerializer() NetDataContractSerializer() NetDataContractSerializer()

Inicializa una nueva instancia de la clase NetDataContractSerializer.Initializes a new instance of the NetDataContractSerializer class.

NetDataContractSerializer(StreamingContext) NetDataContractSerializer(StreamingContext) NetDataContractSerializer(StreamingContext) NetDataContractSerializer(StreamingContext)

Inicializa una instancia nueva de la clase NetDataContractSerializer con los datos de contexto de transmisión por secuencias proporcionados.Initializes a new instance of the NetDataContractSerializer class with the supplied streaming context data.

NetDataContractSerializer(StreamingContext, Int32, Boolean, FormatterAssemblyStyle, ISurrogateSelector) NetDataContractSerializer(StreamingContext, Int32, Boolean, FormatterAssemblyStyle, ISurrogateSelector) NetDataContractSerializer(StreamingContext, Int32, Boolean, FormatterAssemblyStyle, ISurrogateSelector) NetDataContractSerializer(StreamingContext, Int32, Boolean, FormatterAssemblyStyle, ISurrogateSelector)

Inicializa una nueva instancia de la clase NetDataContractSerializer con los datos de contexto proporcionados; además, especifica el número máximo de elementos en el objeto que se va a serializar y los parámetros para especificar si se omiten los datos adicionales, el método de carga de ensamblado y un selector de suplentes.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.

NetDataContractSerializer(String, String) NetDataContractSerializer(String, String) NetDataContractSerializer(String, String) NetDataContractSerializer(String, String)

Inicializa una instancia nueva de la clase NetDataContractSerializer con el elemento raíz y el espacio de nombres de XML proporcionados.Initializes a new instance of the NetDataContractSerializer class with the supplied XML root element and namespace.

NetDataContractSerializer(String, String, StreamingContext, Int32, Boolean, FormatterAssemblyStyle, ISurrogateSelector) NetDataContractSerializer(String, String, StreamingContext, Int32, Boolean, FormatterAssemblyStyle, ISurrogateSelector) NetDataContractSerializer(String, String, StreamingContext, Int32, Boolean, FormatterAssemblyStyle, ISurrogateSelector) NetDataContractSerializer(String, String, StreamingContext, Int32, Boolean, FormatterAssemblyStyle, ISurrogateSelector)

Inicializa una nueva instancia de la clase NetDataContractSerializer con los datos de contexto proporcionados y el nombre y espacio de nombres raíz; además, especifica el número máximo de elementos en el objeto que se va a serializar y los parámetros para especificar si se omiten los datos adicionales, el método de carga de ensamblado y un selector de suplentes.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.

NetDataContractSerializer(XmlDictionaryString, XmlDictionaryString) NetDataContractSerializer(XmlDictionaryString, XmlDictionaryString) NetDataContractSerializer(XmlDictionaryString, XmlDictionaryString) NetDataContractSerializer(XmlDictionaryString, XmlDictionaryString)

Inicializa una instancia nueva de la clase NetDataContractSerializer con dos parámetros de tipo XmlDictionaryString que contienen el elemento raíz y el espacio de nombres utilizados para especificar el contenido.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.

NetDataContractSerializer(XmlDictionaryString, XmlDictionaryString, StreamingContext, Int32, Boolean, FormatterAssemblyStyle, ISurrogateSelector) NetDataContractSerializer(XmlDictionaryString, XmlDictionaryString, StreamingContext, Int32, Boolean, FormatterAssemblyStyle, ISurrogateSelector) NetDataContractSerializer(XmlDictionaryString, XmlDictionaryString, StreamingContext, Int32, Boolean, FormatterAssemblyStyle, ISurrogateSelector) NetDataContractSerializer(XmlDictionaryString, XmlDictionaryString, StreamingContext, Int32, Boolean, FormatterAssemblyStyle, ISurrogateSelector)

Inicializa una nueva instancia de la clase NetDataContractSerializer con los datos de contexto proporcionados y el nombre y espacio de nombres raíz (como parámetros XmlDictionaryString); además, especifica el número máximo de elementos en el objeto que se va a serializar y los parámetros para especificar si se omiten los datos adicionales encontrados, el método de carga de ensamblado y un selector de suplentes.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.

Propiedades

AssemblyFormat AssemblyFormat AssemblyFormat AssemblyFormat

Obtiene un valor que especifica un método para buscar y cargar los ensamblados.Gets a value that specifies a method for locating and loading assemblies.

Binder Binder Binder Binder

Obtiene o establece un objeto que controla la carga de clase.Gets or sets an object that controls class loading.

Context Context Context Context

Obtiene o establece el objeto que permite el paso de datos de contexto, que es útil mientras se serializa o se deserializa.Gets or sets the object that enables the passing of context data that is useful while serializing or deserializing.

IgnoreExtensionDataObject IgnoreExtensionDataObject IgnoreExtensionDataObject IgnoreExtensionDataObject

Obtiene un valor que especifica si se omiten los datos proporcionados por una extensión del objeto.Gets a value that specifies whether data supplied by an extension of the object is ignored.

MaxItemsInObjectGraph MaxItemsInObjectGraph MaxItemsInObjectGraph MaxItemsInObjectGraph

Obtiene el número máximo de elementos permitido en el objeto que se va a serializar.Gets the maximum number of items allowed in the object to be serialized.

SurrogateSelector SurrogateSelector SurrogateSelector SurrogateSelector

Obtiene o establece un objeto que ayuda al formateador al seleccionar un suplente para la serialización.Gets or sets an object that assists the formatter when selecting a surrogate for serialization.

Métodos

Deserialize(Stream) Deserialize(Stream) Deserialize(Stream) Deserialize(Stream)

Deserializa un documento o secuencia XML en un objeto.Deserializes an XML document or stream into an object.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
IsStartObject(XmlDictionaryReader) IsStartObject(XmlDictionaryReader) IsStartObject(XmlDictionaryReader) IsStartObject(XmlDictionaryReader)

Determina si XmlDictionaryReader se coloca sobre un objeto que se puede deserializar utilizando el lector especificado.Determines whether the XmlDictionaryReader is positioned on an object that can be deserialized using the specified reader.

IsStartObject(XmlReader) IsStartObject(XmlReader) IsStartObject(XmlReader) IsStartObject(XmlReader)

Determina si XmlReader se coloca sobre un objeto que se puede deserializar utilizando el lector especificado.Determines whether the XmlReader is positioned on an object that can be deserialized using the specified reader.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
ReadObject(Stream) ReadObject(Stream) ReadObject(Stream) ReadObject(Stream)

Lee la secuencia o el documento XML con Stream y devuelve el objeto deserializado.Reads the XML stream or document with a Stream and returns the deserialized object.

(Inherited from XmlObjectSerializer)
ReadObject(XmlDictionaryReader) ReadObject(XmlDictionaryReader) ReadObject(XmlDictionaryReader) ReadObject(XmlDictionaryReader)

Lee el documento o la secuencia XML con XmlDictionaryReader y devuelve el objeto deserializado.Reads the XML document or stream with an XmlDictionaryReader and returns the deserialized object.

(Inherited from XmlObjectSerializer)
ReadObject(XmlDictionaryReader, Boolean) ReadObject(XmlDictionaryReader, Boolean) ReadObject(XmlDictionaryReader, Boolean) ReadObject(XmlDictionaryReader, Boolean)

Lee la secuencia o el documento XML con XmlDictionaryReader y devuelve el objeto deserializado; también comprueba si los datos del objeto se ajustan al nombre y al espacio de nombres utilizados para crear el serializador.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.

ReadObject(XmlReader) ReadObject(XmlReader) ReadObject(XmlReader) ReadObject(XmlReader)

Lee la secuencia o el documento XML con XmlDictionaryReader y devuelve el objeto deserializado.Reads the XML stream or document with an XmlDictionaryReader and returns the deserialized object.

ReadObject(XmlReader, Boolean) ReadObject(XmlReader, Boolean) ReadObject(XmlReader, Boolean) ReadObject(XmlReader, Boolean)

Lee la secuencia o el documento XML con XmlDictionaryReader y devuelve el objeto deserializado; también comprueba si los datos del objeto se ajustan al nombre y al espacio de nombres utilizados para crear el serializador.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.

Serialize(Stream, Object) Serialize(Stream, Object) Serialize(Stream, Object) Serialize(Stream, Object)

Serializa el gráfico de objetos especificado mediante el sistema de escritura especificado.Serializes the specified object graph using the specified writer.

ToString() ToString() ToString() ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Inherited from Object)
WriteEndObject(XmlDictionaryWriter) WriteEndObject(XmlDictionaryWriter) WriteEndObject(XmlDictionaryWriter) WriteEndObject(XmlDictionaryWriter)

Escribe el elemento XML de cierre mediante XmlDictionaryWriter.Writes the closing XML element using an XmlDictionaryWriter.

WriteEndObject(XmlWriter) WriteEndObject(XmlWriter) WriteEndObject(XmlWriter) WriteEndObject(XmlWriter)

Escribe el elemento XML de cierre mediante XmlWriter.Writes the closing XML element using an XmlWriter.

WriteObject(Stream, Object) WriteObject(Stream, Object) WriteObject(Stream, Object) WriteObject(Stream, Object)

Escribe el contenido completo (inicio, contenido y fin) del objeto en el documento o la secuencia XML con el Streamespecificado.Writes the complete content (start, content, and end) of the object to the XML document or stream with the specified Stream.

(Inherited from XmlObjectSerializer)
WriteObject(XmlDictionaryWriter, Object) WriteObject(XmlDictionaryWriter, Object) WriteObject(XmlDictionaryWriter, Object) WriteObject(XmlDictionaryWriter, Object)

Escribe el contenido completo (inicio, contenido y fin) del objeto en el documento o la secuencia XML con el XmlDictionaryWriterespecificado.Writes the complete content (start, content, and end) of the object to the XML document or stream with the specified XmlDictionaryWriter.

(Inherited from XmlObjectSerializer)
WriteObject(XmlWriter, Object) WriteObject(XmlWriter, Object) WriteObject(XmlWriter, Object) WriteObject(XmlWriter, Object)

Escribe todo el contenido (inicio, contenido y fin) del objeto en el documento o la secuencia XML con el XmlWriter especificado.Writes the complete content (start, content, and end) of the object to the XML document or stream with the specified XmlWriter.

WriteObjectContent(XmlDictionaryWriter, Object) WriteObjectContent(XmlDictionaryWriter, Object) WriteObjectContent(XmlDictionaryWriter, Object) WriteObjectContent(XmlDictionaryWriter, Object)

Escribe el contenido XML mediante XmlDictionaryWriter.Writes the XML content using an XmlDictionaryWriter.

WriteObjectContent(XmlWriter, Object) WriteObjectContent(XmlWriter, Object) WriteObjectContent(XmlWriter, Object) WriteObjectContent(XmlWriter, Object)

Escribe el contenido XML mediante XmlWriter.Writes the XML content using an XmlWriter.

WriteStartObject(XmlDictionaryWriter, Object) WriteStartObject(XmlDictionaryWriter, Object) WriteStartObject(XmlDictionaryWriter, Object) WriteStartObject(XmlDictionaryWriter, Object)

Escribe el elemento XML de apertura mediante XmlDictionaryWriter.Writes the opening XML element using an XmlDictionaryWriter.

WriteStartObject(XmlWriter, Object) WriteStartObject(XmlWriter, Object) WriteStartObject(XmlWriter, Object) WriteStartObject(XmlWriter, Object)

Escribe el elemento XML de apertura mediante XmlWriter.Writes the opening XML element using an XmlWriter.

Se aplica a

Consulte también: