XmlObjectSerializer Clase

Definición

Proporciona la clase base usada para serializar objetos como secuencias XML o documentos.Provides the base class used to serialize objects as XML streams or documents. Esta clase es abstracta.This class is abstract.

public ref class XmlObjectSerializer abstract
public abstract class XmlObjectSerializer
type XmlObjectSerializer = class
Public MustInherit Class XmlObjectSerializer
Herencia
XmlObjectSerializer
Derivado

Ejemplos

El ejemplo siguiente muestra un método denominado WriteObjectWithInstance que incluye un XmlObjectSerializer como parámetro.The following example shows a method named WriteObjectWithInstance that includes an XmlObjectSerializer as a parameter. El método serializa un objeto con DataContractSerializer o NetDataContractSerializer llamando al método WriteObject.The method serializes an object using either the DataContractSerializer or NetDataContractSerializer by calling the WriteObject method.

public class Test
{
    private void WriteObjectWithInstance(XmlObjectSerializer xm, Company graph,
       string fileName)
    {
        // Use either the XmlDataContractSerializer or NetDataContractSerializer,
        // or any other class that inherits from XmlObjectSerializer to write with.
        Console.WriteLine(xm.GetType());
        FileStream fs = new FileStream(fileName, FileMode.Create);
        XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(fs);
        xm.WriteObject(writer, graph);
        Console.WriteLine("Done writing {0}", fileName);
    }

    private void Run()
    {
        // Create the object to write to a file.
        Company graph = new Company();
        graph.Name = "cohowinery.com";

        // Create a DataContractSerializer and a NetDataContractSerializer.
        // Pass either one to the WriteObjectWithInstance method.
        DataContractSerializer dcs = new DataContractSerializer(typeof(Company));
        NetDataContractSerializer ndcs = new NetDataContractSerializer();
        WriteObjectWithInstance(dcs, graph, @"datacontract.xml");
        WriteObjectWithInstance(ndcs, graph, @"netDatacontract.xml");
    }

    [DataContract]
    public class Company
    {
        [DataMember]
        public string Name;
    }

    static void Main()
    {
        try
        {
            Console.WriteLine("Starting");
            Test t = new Test();
            t.Run();
            Console.WriteLine("Done");
            Console.ReadLine();
        }

        catch (InvalidDataContractException iExc)
        {
            Console.WriteLine("You have an invalid data contract: ");
            Console.WriteLine(iExc.Message);
            Console.ReadLine();
        }

        catch (SerializationException serExc)
        {
            Console.WriteLine("There is a problem with the instance:");
            Console.WriteLine(serExc.Message);
            Console.ReadLine();
        }

        catch (QuotaExceededException qExc)
        {
            Console.WriteLine("The quota has been exceeded");
            Console.WriteLine(qExc.Message);
            Console.ReadLine();
        }
        catch (Exception exc)
        {
            Console.WriteLine(exc.Message);
            Console.WriteLine(exc.ToString());
            Console.ReadLine();
        }
    }
Public Class Test
    
    Private Sub WriteObjectWithInstance(ByVal xm As XmlObjectSerializer, _
      ByVal graph As Company, ByVal fileName As String) 
        ' Use either the XmlDataContractSerializer or NetDataContractSerializer,
        ' or any other class that inherits from XmlObjectSerializer to write with.
        Console.WriteLine(xm.GetType())
        Dim fs As New FileStream(fileName, FileMode.Create)
        Dim writer As XmlDictionaryWriter = XmlDictionaryWriter.CreateTextWriter(fs)
        xm.WriteObject(writer, graph)
        Console.WriteLine("Done writing {0}", fileName)
    
    End Sub 
    
    
    Private Sub Run() 
        ' Create the object to write to a file.
        Dim graph As New Company()
        graph.Name = "cohowinery.com"
        
        ' Create a DataContractSerializer and a NetDataContractSerializer.
        ' Pass either one to the WriteObjectWithInstance method.
        Dim dcs As New DataContractSerializer(GetType(Company))
        Dim ndcs As New NetDataContractSerializer()
        WriteObjectWithInstance(dcs, graph, "datacontract.xml")
        WriteObjectWithInstance(ndcs, graph, "netDatacontract.xml")
    
    End Sub 
    
    <DataContract()>  _
    Public Class Company
        <DataMember()>  _
        Public Name As String
    End Class 
    
    
    Shared Sub Main() 
        Try
            Console.WriteLine("Starting")
            Dim t As New Test()
            t.Run()
            Console.WriteLine("Done")
            Console.ReadLine()
        
        Catch iExc As InvalidDataContractException
            Console.WriteLine("You have an invalid data contract: ")
            Console.WriteLine(iExc.Message)
            Console.ReadLine()
        
        Catch serExc As SerializationException
            Console.WriteLine("There is a problem with the instance:")
            Console.WriteLine(serExc.Message)
            Console.ReadLine()
        
        Catch qExc As QuotaExceededException
            Console.WriteLine("The quota has been exceeded")
            Console.WriteLine(qExc.Message)
            Console.ReadLine()
        Catch exc As Exception
            Console.WriteLine(exc.Message)
            Console.WriteLine(exc.ToString())
            Console.ReadLine()
        End Try
    
    End Sub 
End Class 

Comentarios

Extienda XmlObjectSerializer para crear su propio serializador a fin de serializar y deserializar objetos.Extend the XmlObjectSerializer to create your own serializer to serialize and deserialize objects. La clase DataContractSerializer y la clase NetDataContractSerializer se heredan de XmlObjectSerializer y se usan para serializar y deserializar objetos que se ajustan a las reglas del contrato de datos (objetos creados con DataContractAttribute y DataMemberAttribute).Both the DataContractSerializer class and the NetDataContractSerializer class inherit from the XmlObjectSerializer and are used to serialize and deserialize objects that conform to data contract rules (objects created using the DataContractAttribute and the DataMemberAttribute).

Notas a los implementadores

Al heredar de XmlObjectSerializer, es necesario invalidar los miembros siguientes: WriteStartObject(XmlDictionaryWriter, Object), WriteObjectContent(XmlDictionaryWriter, Object), WriteEndObject(XmlDictionaryWriter).When you inherit from XmlObjectSerializer, you must override the following members: WriteStartObject(XmlDictionaryWriter, Object), WriteObjectContent(XmlDictionaryWriter, Object), WriteEndObject(XmlDictionaryWriter). Además, deben implementarse los métodos IsStartObject y ReadObject para leer y serializar.Additionally, the IsStartObject and ReadObject methods must be implemented for reading and deserializing.

Constructores

XmlObjectSerializer()

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

Métodos

Equals(Object)

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

(Heredado de Object)
GetHashCode()

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

(Heredado de Object)
GetType()

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

(Heredado de Object)
IsStartObject(XmlDictionaryReader)

Obtiene un valor que especifica si XmlDictionaryReader está colocado sobre un elemento XML que se puede leer.Gets a value that specifies whether the XmlDictionaryReader is positioned over an XML element that can be read.

IsStartObject(XmlReader)

Obtiene un valor que especifica si XmlReader está colocado sobre un elemento XML que se puede leer.Gets a value that specifies whether the XmlReader is positioned over an XML element that can be read.

MemberwiseClone()

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

(Heredado de Object)
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.

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.

ReadObject(XmlDictionaryReader, Boolean)

Lee la secuencia o el documento XML con XmlDictionaryReader y devuelve el objeto deserializado; también le permite especificar si el serializador puede leer los datos antes de intentar leerlos.Reads the XML stream or document with an XmlDictionaryReader and returns the deserialized object; it also enables you to specify whether the serializer can read the data before attempting to read it.

ReadObject(XmlReader)

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

ReadObject(XmlReader, Boolean)

Lee el documento o la secuencia XML con XmlReader y devuelve el objeto deserializado; también le permite especificar si el serializador puede leer los datos antes de intentar leerlos.Reads the XML document or stream with an XmlReader and returns the deserialized object; it also enables you to specify whether the serializer can read the data before attempting to read it.

ToString()

Devuelve un valor de tipo string que representa el objeto actual.Returns a string that represents the current object.

(Heredado de Object)
WriteEndObject(XmlDictionaryWriter)

Escribe el fin de los datos de objeto como un elemento XML de cierre en el documento o la secuencia XML con XmlDictionaryWriter.Writes the end of the object data as a closing XML element to the XML document or stream with an XmlDictionaryWriter.

WriteEndObject(XmlWriter)

Escribe el fin de los datos de objeto como un elemento XML de cierre en el documento o la secuencia XML con XmlWriter.Writes the end of the object data as a closing XML element to the XML document or stream with an XmlWriter.

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.

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.

WriteObject(XmlWriter, Object)

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

WriteObjectContent(XmlDictionaryWriter, Object)

Escribe sólo el contenido del objeto en el documento o la secuencia XML con el XmlDictionaryWriter especificado.Writes only the content of the object to the XML document or stream using the specified XmlDictionaryWriter.

WriteObjectContent(XmlWriter, Object)

Escribe sólo el contenido del objeto en el documento o la secuencia XML con el XmlWriter especificado.Writes only the content of the object to the XML document or stream with the specified XmlWriter.

WriteStartObject(XmlDictionaryWriter, Object)

Escribe el inicio de los datos del objeto como un elemento XML de apertura con el XmlDictionaryWriter especificado.Writes the start of the object's data as an opening XML element using the specified XmlDictionaryWriter.

WriteStartObject(XmlWriter, Object)

Escribe el inicio de los datos del objeto como un elemento XML de apertura con el XmlWriter especificado.Writes the start of the object's data as an opening XML element using the specified XmlWriter.

Se aplica a

Consulte también: