XmlSerializer XmlSerializer XmlSerializer XmlSerializer Class

Definición

Serializa y deserializa objetos en y desde documentos XML.Serializes and deserializes objects into and from XML documents. XmlSerializer permite controlar el modo en que se codifican los objetos en XML.The XmlSerializer enables you to control how objects are encoded into XML.

public ref class XmlSerializer
public class XmlSerializer
type XmlSerializer = class
Public Class XmlSerializer
Herencia
XmlSerializerXmlSerializerXmlSerializerXmlSerializer

Ejemplos

El siguiente ejemplo contiene dos clases principales: PurchaseOrder y Test.The following example contains two main classes: PurchaseOrder and Test. La PurchaseOrder clase contiene información sobre una sola compra.The PurchaseOrder class contains information about a single purchase. La Test clase contiene los métodos que crean el pedido de compra, y que lea el pedido de compra creado.The Test class contains the methods that create the purchase order, and that read the created purchase order.

#using <System.Xml.dll>
#using <System.dll>

using namespace System;
using namespace System::Xml;
using namespace System::Xml::Serialization;
using namespace System::IO;
ref class Address;
ref class OrderedItem;

/* The XmlRootAttribute allows you to set an alternate name 
   (PurchaseOrder) of the XML element, the element namespace; by 
   default, the XmlSerializer uses the class name. The attribute 
   also allows you to set the XML namespace for the element.  Lastly,
   the attribute sets the IsNullable property, which specifies whether 
   the xsi:null attribute appears if the class instance is set to 
   a null reference. */

[XmlRootAttribute("PurchaseOrder",Namespace="http://www.cpandl.com",
IsNullable=false)]
public ref class PurchaseOrder
{
public:
   Address^ ShipTo;
   String^ OrderDate;

   /* The XmlArrayAttribute changes the XML element name
       from the default of "OrderedItems" to "Items". */

   [XmlArrayAttribute("Items")]
   array<OrderedItem^>^OrderedItems;
   Decimal SubTotal;
   Decimal ShipCost;
   Decimal TotalCost;
};

public ref class Address
{
public:

   /* The XmlAttribute instructs the XmlSerializer to serialize the Name
         field as an XML attribute instead of an XML element (the default
         behavior). */

   [XmlAttributeAttribute]
   String^ Name;
   String^ Line1;

   /* Setting the IsNullable property to false instructs the 
         XmlSerializer that the XML attribute will not appear if 
         the City field is set to a null reference. */

   [XmlElementAttribute(IsNullable=false)]
   String^ City;
   String^ State;
   String^ Zip;
};

public ref class OrderedItem
{
public:
   String^ ItemName;
   String^ Description;
   Decimal UnitPrice;
   int Quantity;
   Decimal LineTotal;

   /* Calculate is a custom method that calculates the price per item,
         and stores the value in a field. */
   void Calculate()
   {
      LineTotal = UnitPrice * Quantity;
   }

};

public ref class Test
{
public:
   static void main()
   {
      // Read and write purchase orders.
      Test^ t = gcnew Test;
      t->CreatePO( "po.xml" );
      t->ReadPO( "po.xml" );
   }

private:
   void CreatePO( String^ filename )
   {
      // Create an instance of the XmlSerializer class;
      // specify the type of object to serialize.
      XmlSerializer^ serializer = gcnew XmlSerializer( PurchaseOrder::typeid );
      TextWriter^ writer = gcnew StreamWriter( filename );
      PurchaseOrder^ po = gcnew PurchaseOrder;

      // Create an address to ship and bill to.
      Address^ billAddress = gcnew Address;
      billAddress->Name = "Teresa Atkinson";
      billAddress->Line1 = "1 Main St.";
      billAddress->City = "AnyTown";
      billAddress->State = "WA";
      billAddress->Zip = "00000";

      // Set ShipTo and BillTo to the same addressee.
      po->ShipTo = billAddress;
      po->OrderDate = System::DateTime::Now.ToLongDateString();

      // Create an OrderedItem object.
      OrderedItem^ i1 = gcnew OrderedItem;
      i1->ItemName = "Widget S";
      i1->Description = "Small widget";
      i1->UnitPrice = (Decimal)5.23;
      i1->Quantity = 3;
      i1->Calculate();

      // Insert the item into the array.
      array<OrderedItem^>^items = {i1};
      po->OrderedItems = items;

      // Calculate the total cost.
      Decimal subTotal = Decimal(0);
      System::Collections::IEnumerator^ myEnum = items->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         OrderedItem^ oi = safe_cast<OrderedItem^>(myEnum->Current);
         subTotal = subTotal + oi->LineTotal;
      }

      po->SubTotal = subTotal;
      po->ShipCost = (Decimal)12.51;
      po->TotalCost = po->SubTotal + po->ShipCost;

      // Serialize the purchase order, and close the TextWriter.
      serializer->Serialize( writer, po );
      writer->Close();
   }

protected:
   void ReadPO( String^ filename )
   {
      // Create an instance of the XmlSerializer class;
      // specify the type of object to be deserialized.
      XmlSerializer^ serializer = gcnew XmlSerializer( PurchaseOrder::typeid );

      /* If the XML document has been altered with unknown 
            nodes or attributes, handle them with the 
            UnknownNode and UnknownAttribute events.*/
      serializer->UnknownNode += gcnew XmlNodeEventHandler( this, &Test::serializer_UnknownNode );
      serializer->UnknownAttribute += gcnew XmlAttributeEventHandler( this, &Test::serializer_UnknownAttribute );

      // A FileStream is needed to read the XML document.
      FileStream^ fs = gcnew FileStream( filename,FileMode::Open );

      // Declare an object variable of the type to be deserialized.
      PurchaseOrder^ po;

      /* Use the Deserialize method to restore the object's state with
            data from the XML document. */
      po = dynamic_cast<PurchaseOrder^>(serializer->Deserialize( fs ));

      // Read the order date.
      Console::WriteLine( "OrderDate: {0}", po->OrderDate );

      // Read the shipping address.
      Address^ shipTo = po->ShipTo;
      ReadAddress( shipTo, "Ship To:" );

      // Read the list of ordered items.
      array<OrderedItem^>^items = po->OrderedItems;
      Console::WriteLine( "Items to be shipped:" );
      System::Collections::IEnumerator^ myEnum1 = items->GetEnumerator();
      while ( myEnum1->MoveNext() )
      {
         OrderedItem^ oi = safe_cast<OrderedItem^>(myEnum1->Current);
         Console::WriteLine( "\t{0}\t{1}\t{2}\t{3}\t{4}", oi->ItemName, oi->Description, oi->UnitPrice, oi->Quantity, oi->LineTotal );
      }

      Console::WriteLine( "\t\t\t\t\t Subtotal\t{0}", po->SubTotal );
      Console::WriteLine( "\t\t\t\t\t Shipping\t{0}", po->ShipCost );
      Console::WriteLine( "\t\t\t\t\t Total\t\t{0}", po->TotalCost );
   }

   void ReadAddress( Address^ a, String^ label )
   {
      // Read the fields of the Address object.
      Console::WriteLine( label );
      Console::WriteLine( "\t{0}", a->Name );
      Console::WriteLine( "\t{0}", a->Line1 );
      Console::WriteLine( "\t{0}", a->City );
      Console::WriteLine( "\t{0}", a->State );
      Console::WriteLine( "\t{0}", a->Zip );
      Console::WriteLine();
   }

private:
   void serializer_UnknownNode( Object^ /*sender*/, XmlNodeEventArgs^ e )
   {
      Console::WriteLine( "Unknown Node:{0}\t{1}", e->Name, e->Text );
   }

   void serializer_UnknownAttribute( Object^ /*sender*/, XmlAttributeEventArgs^ e )
   {
      System::Xml::XmlAttribute^ attr = e->Attr;
      Console::WriteLine( "Unknown attribute {0}='{1}'", attr->Name, attr->Value );
   }
};

int main()
{
   Test::main();
}
using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

/* The XmlRootAttribute allows you to set an alternate name 
   (PurchaseOrder) of the XML element, the element namespace; by 
   default, the XmlSerializer uses the class name. The attribute 
   also allows you to set the XML namespace for the element.  Lastly,
   the attribute sets the IsNullable property, which specifies whether 
   the xsi:null attribute appears if the class instance is set to 
   a null reference. */
[XmlRootAttribute("PurchaseOrder", Namespace="http://www.cpandl.com", 
IsNullable = false)]
public class PurchaseOrder
{
   public Address ShipTo;
   public string OrderDate; 
   /* The XmlArrayAttribute changes the XML element name
    from the default of "OrderedItems" to "Items". */
   [XmlArrayAttribute("Items")]
   public OrderedItem[] OrderedItems;
   public decimal SubTotal;
   public decimal ShipCost;
   public decimal TotalCost;   
}
 
public class Address
{
   /* The XmlAttribute instructs the XmlSerializer to serialize the Name
      field as an XML attribute instead of an XML element (the default
      behavior). */
   [XmlAttribute]
   public string Name;
   public string Line1;

   /* Setting the IsNullable property to false instructs the 
      XmlSerializer that the XML attribute will not appear if 
      the City field is set to a null reference. */
   [XmlElementAttribute(IsNullable = false)]
   public string City;
   public string State;
   public string Zip;
}
 
public class OrderedItem
{
   public string ItemName;
   public string Description;
   public decimal UnitPrice;
   public int Quantity;
   public decimal LineTotal;

   /* Calculate is a custom method that calculates the price per item,
      and stores the value in a field. */
   public void Calculate()
   {
      LineTotal = UnitPrice * Quantity;
   }
}
 
public class Test
{
   public static void Main()
   {
      // Read and write purchase orders.
      Test t = new Test();
      t.CreatePO("po.xml");
      t.ReadPO("po.xml");
   }

   private void CreatePO(string filename)
   {
      // Create an instance of the XmlSerializer class;
      // specify the type of object to serialize.
      XmlSerializer serializer = 
      new XmlSerializer(typeof(PurchaseOrder));
      TextWriter writer = new StreamWriter(filename);
      PurchaseOrder po=new PurchaseOrder();
       
      // Create an address to ship and bill to.
      Address billAddress = new Address();
      billAddress.Name = "Teresa Atkinson";
      billAddress.Line1 = "1 Main St.";
      billAddress.City = "AnyTown";
      billAddress.State = "WA";
      billAddress.Zip = "00000";
      // Set ShipTo and BillTo to the same addressee.
      po.ShipTo = billAddress;
      po.OrderDate = System.DateTime.Now.ToLongDateString();
 
      // Create an OrderedItem object.
      OrderedItem i1 = new OrderedItem();
      i1.ItemName = "Widget S";
      i1.Description = "Small widget";
      i1.UnitPrice = (decimal) 5.23;
      i1.Quantity = 3;
      i1.Calculate();
 
      // Insert the item into the array.
      OrderedItem [] items = {i1};
      po.OrderedItems = items;
      // Calculate the total cost.
      decimal subTotal = new decimal();
      foreach(OrderedItem oi in items)
      {
         subTotal += oi.LineTotal;
      }
      po.SubTotal = subTotal;
      po.ShipCost = (decimal) 12.51; 
      po.TotalCost = po.SubTotal + po.ShipCost; 
      // Serialize the purchase order, and close the TextWriter.
      serializer.Serialize(writer, po);
      writer.Close();
   }
 
   protected void ReadPO(string filename)
   {
      // Create an instance of the XmlSerializer class;
      // specify the type of object to be deserialized.
      XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder));
      /* If the XML document has been altered with unknown 
      nodes or attributes, handle them with the 
      UnknownNode and UnknownAttribute events.*/
      serializer.UnknownNode+= new 
      XmlNodeEventHandler(serializer_UnknownNode);
      serializer.UnknownAttribute+= new 
      XmlAttributeEventHandler(serializer_UnknownAttribute);
   
      // A FileStream is needed to read the XML document.
      FileStream fs = new FileStream(filename, FileMode.Open);
      // Declare an object variable of the type to be deserialized.
      PurchaseOrder po;
      /* Use the Deserialize method to restore the object's state with
      data from the XML document. */
      po = (PurchaseOrder) serializer.Deserialize(fs);
      // Read the order date.
      Console.WriteLine ("OrderDate: " + po.OrderDate);
  
      // Read the shipping address.
      Address shipTo = po.ShipTo;
      ReadAddress(shipTo, "Ship To:");
      // Read the list of ordered items.
      OrderedItem [] items = po.OrderedItems;
      Console.WriteLine("Items to be shipped:");
      foreach(OrderedItem oi in items)
      {
         Console.WriteLine("\t"+
         oi.ItemName + "\t" + 
         oi.Description + "\t" +
         oi.UnitPrice + "\t" +
         oi.Quantity + "\t" +
         oi.LineTotal);
      }
      // Read the subtotal, shipping cost, and total cost.
      Console.WriteLine("\t\t\t\t\t Subtotal\t" + po.SubTotal);
      Console.WriteLine("\t\t\t\t\t Shipping\t" + po.ShipCost); 
      Console.WriteLine("\t\t\t\t\t Total\t\t" + po.TotalCost);
   }
 
   protected void ReadAddress(Address a, string label)
   {
      // Read the fields of the Address object.
      Console.WriteLine(label);
      Console.WriteLine("\t"+ a.Name );
      Console.WriteLine("\t" + a.Line1);
      Console.WriteLine("\t" + a.City);
      Console.WriteLine("\t" + a.State);
      Console.WriteLine("\t" + a.Zip );
      Console.WriteLine();
   }

   private void serializer_UnknownNode
   (object sender, XmlNodeEventArgs e)
   {
      Console.WriteLine("Unknown Node:" +   e.Name + "\t" + e.Text);
   }

   private void serializer_UnknownAttribute
   (object sender, XmlAttributeEventArgs e)
   {
      System.Xml.XmlAttribute attr = e.Attr;
      Console.WriteLine("Unknown attribute " + 
      attr.Name + "='" + attr.Value + "'");
   }
}
Imports System
Imports System.Xml
Imports System.Xml.Serialization
Imports System.IO
Imports Microsoft.VisualBasic


' The XmlRootAttribute allows you to set an alternate name
' (PurchaseOrder) of the XML element, the element namespace; by
' default, the XmlSerializer uses the class name. The attribute
' also allows you to set the XML namespace for the element.  Lastly,
' the attribute sets the IsNullable property, which specifies whether
' the xsi:null attribute appears if the class instance is set to
' a null reference. 
<XmlRootAttribute("PurchaseOrder", _
 Namespace := "http://www.cpandl.com", IsNullable := False)> _
Public Class PurchaseOrder
    
    Public ShipTo As Address
    Public OrderDate As String
    ' The XmlArrayAttribute changes the XML element name
    ' from the default of "OrderedItems" to "Items". 
    <XmlArrayAttribute("Items")> _
    Public OrderedItems() As OrderedItem
    Public SubTotal As Decimal
    Public ShipCost As Decimal
    Public TotalCost As Decimal
End Class 'PurchaseOrder


Public Class Address
    ' The XmlAttribute instructs the XmlSerializer to serialize the Name
    ' field as an XML attribute instead of an XML element (the default
    ' behavior). 
    <XmlAttribute()> _
    Public Name As String
    Public Line1 As String
    
    ' Setting the IsNullable property to false instructs the
    ' XmlSerializer that the XML attribute will not appear if
    ' the City field is set to a null reference. 
    <XmlElementAttribute(IsNullable := False)> _
    Public City As String
    Public State As String
    Public Zip As String
End Class 'Address


Public Class OrderedItem
    Public ItemName As String
    Public Description As String
    Public UnitPrice As Decimal
    Public Quantity As Integer
    Public LineTotal As Decimal
    
    
    ' Calculate is a custom method that calculates the price per item,
    ' and stores the value in a field. 
    Public Sub Calculate()
        LineTotal = UnitPrice * Quantity
    End Sub 'Calculate
End Class 'OrderedItem


Public Class Test
    
   Public Shared Sub Main()
      ' Read and write purchase orders.
      Dim t As New Test()
      t.CreatePO("po.xml")
      t.ReadPO("po.xml")
   End Sub 'Main
    
   Private Sub CreatePO(filename As String)
      ' Create an instance of the XmlSerializer class;
      ' specify the type of object to serialize.
      Dim serializer As New XmlSerializer(GetType(PurchaseOrder))
      Dim writer As New StreamWriter(filename)
      Dim po As New PurchaseOrder()
        
      ' Create an address to ship and bill to.
      Dim billAddress As New Address()
      billAddress.Name = "Teresa Atkinson"
      billAddress.Line1 = "1 Main St."
      billAddress.City = "AnyTown"
      billAddress.State = "WA"
      billAddress.Zip = "00000"
      ' Set ShipTo and BillTo to the same addressee.
      po.ShipTo = billAddress
      po.OrderDate = System.DateTime.Now.ToLongDateString()
        
      ' Create an OrderedItem object.
      Dim i1 As New OrderedItem()
      i1.ItemName = "Widget S"
      i1.Description = "Small widget"
      i1.UnitPrice = CDec(5.23)
      i1.Quantity = 3
      i1.Calculate()
        
      ' Insert the item into the array.
      Dim items(0) As OrderedItem
      items(0) = i1
      po.OrderedItems = items
      ' Calculate the total cost.
      Dim subTotal As New Decimal()
      Dim oi As OrderedItem
      For Each oi In  items
         subTotal += oi.LineTotal
      Next oi
      po.SubTotal = subTotal
      po.ShipCost = CDec(12.51)
      po.TotalCost = po.SubTotal + po.ShipCost
      ' Serialize the purchase order, and close the TextWriter.
      serializer.Serialize(writer, po)
      writer.Close()
   End Sub 'CreatePO
    
   Protected Sub ReadPO(filename As String)
      ' Create an instance of the XmlSerializer class;
      ' specify the type of object to be deserialized.
      Dim serializer As New XmlSerializer(GetType(PurchaseOrder))
      ' If the XML document has been altered with unknown
      ' nodes or attributes, handle them with the
      ' UnknownNode and UnknownAttribute events.
      AddHandler serializer.UnknownNode, AddressOf serializer_UnknownNode
      AddHandler serializer.UnknownAttribute, AddressOf serializer_UnknownAttribute
      
      ' A FileStream is needed to read the XML document.
      Dim fs As New FileStream(filename, FileMode.Open)
      ' Declare an object variable of the type to be deserialized.
      Dim po As PurchaseOrder
      ' Use the Deserialize method to restore the object's state with
      ' data from the XML document. 
      po = CType(serializer.Deserialize(fs), PurchaseOrder)
      ' Read the order date.
      Console.WriteLine(("OrderDate: " & po.OrderDate))
        
      ' Read the shipping address.
      Dim shipTo As Address = po.ShipTo
      ReadAddress(shipTo, "Ship To:")
      ' Read the list of ordered items.
      Dim items As OrderedItem() = po.OrderedItems
      Console.WriteLine("Items to be shipped:")
      Dim oi As OrderedItem
      For Each oi In  items
         Console.WriteLine((ControlChars.Tab & oi.ItemName & ControlChars.Tab & _
         oi.Description & ControlChars.Tab & oi.UnitPrice & ControlChars.Tab & _
         oi.Quantity & ControlChars.Tab & oi.LineTotal))
      Next oi
      ' Read the subtotal, shipping cost, and total cost.
      Console.WriteLine(( New String(ControlChars.Tab, 5) & _
      " Subtotal"  & ControlChars.Tab & po.SubTotal))
      Console.WriteLine(New String(ControlChars.Tab, 5) & _
      " Shipping" & ControlChars.Tab & po.ShipCost )
      Console.WriteLine( New String(ControlChars.Tab, 5) & _
      " Total" &  New String(ControlChars.Tab, 2) & po.TotalCost)
    End Sub 'ReadPO
    
    Protected Sub ReadAddress(a As Address, label As String)
      ' Read the fields of the Address object.
      Console.WriteLine(label)
      Console.WriteLine(ControlChars.Tab & a.Name)
      Console.WriteLine(ControlChars.Tab & a.Line1)
      Console.WriteLine(ControlChars.Tab & a.City)
      Console.WriteLine(ControlChars.Tab & a.State)
      Console.WriteLine(ControlChars.Tab & a.Zip)
      Console.WriteLine()
    End Sub 'ReadAddress
        
    Private Sub serializer_UnknownNode(sender As Object, e As XmlNodeEventArgs)
        Console.WriteLine(("Unknown Node:" & e.Name & ControlChars.Tab & e.Text))
    End Sub 'serializer_UnknownNode
    
    
    Private Sub serializer_UnknownAttribute(sender As Object, e As XmlAttributeEventArgs)
        Dim attr As System.Xml.XmlAttribute = e.Attr
        Console.WriteLine(("Unknown attribute " & attr.Name & "='" & attr.Value & "'"))
    End Sub 'serializer_UnknownAttribute
End Class 'Test

Comentarios

La serialización XML es el proceso mediante el cual los campos y propiedades públicos de un objeto se convierten a un formato de serie (en este caso, XML) a efectos de almacenamiento o transporte.XML serialization is the process of converting an object's public properties and fields to a serial format (in this case, XML) for storage or transport. Deserialización vuelve a crea el objeto en su estado original de la salida XML.Deserialization re-creates the object in its original state from the XML output. Se puede considerar la serialización como una manera de guardar el estado de un objeto en una secuencia o búfer.You can think of serialization as a way of saving the state of an object into a stream or buffer. Por ejemplo, ASP.NET usa el XmlSerializer clase para codificar los mensajes de servicio Web XML.For example, ASP.NET uses the XmlSerializer class to encode XML Web service messages.

Los datos de los objetos se describen utilizando construcciones de lenguaje de programación como, por ejemplo, clases, campos, propiedades, tipos primitivos, matrices e incluso XML incrustado en forma de objetos XmlElement o XmlAttribute.The data in your objects is described using programming language constructs like classes, fields, properties, primitive types, arrays, and even embedded XML in the form of XmlElement or XmlAttribute objects. Tiene la opción de crear clases propias, anotadas con atributos o utilizando el XML Schema Definition Tool (Xsd.exe) para generar las clases basadas en un documento de esquema XML (XSD) de la definición existente.You have the option of creating your own classes, annotated with attributes, or using the XML Schema Definition Tool (Xsd.exe) to generate the classes based on an existing XML Schema definition (XSD) document. Si tiene un esquema XML, puede ejecutar Xsd.exe para generar un conjunto de clases fuertemente tipadas para el esquema y anotadas con atributos que se adhiere al esquema cuando se serializa.If you have an XML Schema, you can run the Xsd.exe to produce a set of classes that are strongly typed to the schema and annotated with attributes to adhere to the schema when serialized.

Para transferir datos entre los objetos y XML requiere una asignación de las construcciones de lenguaje de programación al esquema XML y del esquema XML a las construcciones de lenguaje de programación.To transfer data between objects and XML requires a mapping from the programming language constructs to XML schema and from the XML schema to the programming language constructs. El XmlSerializer y herramientas relacionadas como Xsd.exe constituyen el puente entre estas dos tecnologías tanto en tiempo de diseño y tiempo de ejecución.The XmlSerializer and related tools like Xsd.exe provide the bridge between these two technologies at both design time and runtime. En tiempo de diseño, utilice Xsd.exe para generar un documento de esquema XML (.xsd) de sus clases personalizadas o para generar clases a partir de un esquema determinado.At design time, use the Xsd.exe to produce an XML schema document (.xsd) from your custom classes or to produce classes from a given schema. En cualquier caso, las clases se anotan con atributos personalizados para indicar el XmlSerializer cómo asignar entre el sistema de esquema XML y common language runtime.In either case, the classes are annotated with custom attributes to instruct the XmlSerializer how to map between the XML schema system and the common language runtime. En tiempo de ejecución, se pueden serializar instancias de las clases en documentos XML que siguen el esquema dado.At runtime, instances of the classes can be serialized into XML documents that follow the given schema. Del mismo modo, estos documentos XML se pueden deserializar en objetos en tiempo de ejecución.Likewise, these XML documents can be deserialized into runtime objects. Tenga en cuenta que el esquema XML es opcional y no es necesario en tiempo de diseño o en tiempo de ejecución.Note that the XML schema is optional, and not required at design time or runtime.

Controlar el XML generadoControlling Generated XML

Para controlar el XML generado, puede aplicar atributos especiales a las clases y miembros.To control the generated XML, you can apply special attributes to classes and members. Por ejemplo, para especificar un nombre de elemento XML diferente, aplique un XmlElementAttribute a un campo público o una propiedad y un conjunto el ElementName propiedad.For example, to specify a different XML element name, apply an XmlElementAttribute to a public field or property, and set the ElementName property. Para obtener una lista completa de atributos similares, vea Attributes That Control XML Serialization.For a complete list of similar attributes, see Attributes That Control XML Serialization. También puede implementar el IXmlSerializable interfaz para controlar el resultado XML.You can also implement the IXmlSerializable interface to control the XML output.

Si el XML generado se ajusta a la sección 5 del documento del Consorcio WWC, protocolo de acceso de objeto Simple (SOAP) 1.1, debe construir el XmlSerializer con un XmlTypeMapping.If the XML generated must conform to section 5 of the World Wide Consortium document, Simple Object Access Protocol (SOAP) 1.1, you must construct the XmlSerializer with an XmlTypeMapping. Para controlar el SOAP XML codificado, use los atributos listados en atributos que controlan la serialización SOAP codificada.To further control the encoded SOAP XML, use the attributes listed in Attributes That Control Encoded SOAP Serialization.

Con el XmlSerializer puede aprovechar las ventajas de trabajar con clases fuertemente tipadas y todavía tiene la flexibilidad de XML.With the XmlSerializer you can take advantage of working with strongly typed classes and still have the flexibility of XML. Utilizar campos o propiedades de tipo XmlElement, XmlAttribute o XmlNode en sus clases fuertemente tipadas, puede leer las partes del documento XML directamente en objetos XML.Using fields or properties of type XmlElement, XmlAttribute or XmlNode in your strongly typed classes, you can read parts of the XML document directly into XML objects.

Si trabaja con esquemas XML extensibles, también puede usar el XmlAnyElementAttribute y XmlAnyAttributeAttribute atributos para serializar y deserializar elementos o atributos que no se encuentran en el esquema original.If you work with extensible XML schemas, you can also use the XmlAnyElementAttribute and XmlAnyAttributeAttribute attributes to serialize and deserialize elements or attributes that are not found in the original schema. Para utilizar los objetos, aplique un XmlAnyElementAttribute a un campo que devuelve una matriz de XmlElement objetos o aplicar una XmlAnyAttributeAttribute a un campo que devuelve una matriz de XmlAttribute objetos.To use the objects, apply an XmlAnyElementAttribute to a field that returns an array of XmlElement objects, or apply an XmlAnyAttributeAttribute to a field that returns an array of XmlAttribute objects.

Si una propiedad o un campo devuelve un objeto complejo como, por ejemplo, una matriz o una instancia de clase, XmlSerializer lo convierte a un elemento anidado en el documento XML principal.If a property or field returns a complex object (such as an array or a class instance), the XmlSerializer converts it to an element nested within the main XML document. Por ejemplo, la primera clase en el código siguiente devuelve una instancia de la segunda clase.For example, the first class in the following code returns an instance of the second class.

Public Class MyClass  
    Public MyObjectProperty As MyObject  
End Class  

Public Class MyObject  
    Public ObjectName As String  
End Class  
public class MyClass  
{  
    public MyObject MyObjectProperty;  
}  
public class MyObject  
{  
    public string ObjectName;  
}  

El serializado, el resultado XML tendrá un aspecto similar al siguiente:The serialized, XML output looks like this:

<MyClass>  
  <MyObjectProperty>  
  <ObjectName>My String</ObjectName>  
  </MyObjectProperty>  
</MyClass>  

Si un esquema incluye un elemento opcional (minOccurs = "0"), o si el esquema incluye un valor predeterminado, tiene dos opciones.If a schema includes an element that is optional (minOccurs = '0'), or if the schema includes a default value, you have two options. Una opción consiste en usar System.ComponentModel.DefaultValueAttribute para especificar el valor predeterminado, tal como se muestra en el código siguiente.One option is to use System.ComponentModel.DefaultValueAttribute to specify the default value, as shown in the following code.

Public Class PurchaseOrder  
    <System.ComponentModel.DefaultValueAttribute ("2002")> _  
    Public Year As String  
End Class  
public class PurchaseOrder  
{  
    [System.ComponentModel.DefaultValueAttribute ("2002")]  
    public string Year;  
}  

Otra opción consiste en usar un patrón especial para crear un campo booleano reconocido por el XmlSerializery para aplicar el XmlIgnoreAttribute al campo.Another option is to use a special pattern to create a Boolean field recognized by the XmlSerializer, and to apply the XmlIgnoreAttribute to the field. El modelo se crea en el formulario de propertyNameSpecified.The pattern is created in the form of propertyNameSpecified. Por ejemplo, si hay un campo denominado "MyFirstName" también crearía un campo denominado "MyFirstNameSpecified" que indica el XmlSerializer si se debe generar el elemento XML denominado "MyFirstName".For example, if there is a field named "MyFirstName" you would also create a field named "MyFirstNameSpecified" that instructs the XmlSerializer whether to generate the XML element named "MyFirstName". Esta implementación se muestra en el ejemplo siguiente.This is shown in the following example.

Public Class OptionalOrder  
    ' This field's value should not be serialized   
    ' if it is uninitialized.  
    Public FirstOrder As String  

    ' Use the XmlIgnoreAttribute to ignore the   
    ' special field named "FirstOrderSpecified".  
    <System.Xml.Serialization.XmlIgnoreAttribute> _  
    Public FirstOrderSpecified As Boolean  
End Class  
public class OptionalOrder  
{  
    // This field should not be serialized   
    // if it is uninitialized.  
    public string FirstOrder;  

    // Use the XmlIgnoreAttribute to ignore the   
    // special field named "FirstOrderSpecified".  
    [System.Xml.Serialization.XmlIgnoreAttribute]  
    public bool FirstOrderSpecified;  
}  

Invalidar la serialización predeterminadaOverriding Default Serialization

También puede invalidar la serialización de cualquier conjunto de objetos y sus campos y propiedades creando uno de los atributos apropiados, y éste se agrega a una instancia de la XmlAttributes clase.You can also override the serialization of any set of objects and their fields and properties by creating one of the appropriate attributes, and adding it to an instance of the XmlAttributes class. Invalidar la serialización de este modo tiene dos usos: en primer lugar, puede controlar y aumentar la serialización de objetos que se encuentran en un archivo DLL, incluso si no tiene acceso al origen; en segundo lugar, puede crear un conjunto de clases serializables pero serializar los objetos de varias maneras.Overriding serialization in this way has two uses: first, you can control and augment the serialization of objects found in a DLL, even if you do not have access to the source; second, you can create one set of serializable classes, but serialize the objects in multiple ways. Para obtener más información, consulte el XmlAttributeOverrides clase y Cómo: Controlar la serialización de clases derivadas.For more details, see the XmlAttributeOverrides class and How to: Control Serialization of Derived Classes.

Para serializar un objeto, llame a la Serialize método.To serialize an object, call the Serialize method. Para deserializar un objeto, llame a la Deserialize método.To deserialize an object, call the Deserialize method.

Para agregar espacios de nombres XML a un documento XML, vea XmlSerializerNamespaces.To add XML namespaces to an XML document, see XmlSerializerNamespaces.

Nota

El XmlSerializer da un trato especial a las clases que implementan IEnumerable o ICollection.The XmlSerializer gives special treatment to classes that implement IEnumerable or ICollection. Una clase que implementa IEnumerable debe implementar un método Add público que requiere un solo parámetro.A class that implements IEnumerable must implement a public Add method that takes a single parameter. El Add parámetro del método debe ser del mismo tipo que devuelve el Current propiedad en el valor devuelto de GetEnumerator, o una de las bases de dicho tipo.The Add method's parameter must be of the same type as is returned from the Current property on the value returned from GetEnumerator, or one of that type's bases. Una clase que implementa ICollection (como CollectionBase) además IEnumerable debe tener una pública Item indizar la propiedad (indizador en C#) que toma un entero y debe tener una pública Count propiedad de tipo entero.A class that implements ICollection (such as CollectionBase) in addition to IEnumerable must have a public Item indexed property (indexer in C#) that takes an integer, and it must have a public Count property of type integer. El parámetro para el Add método debe ser del mismo tipo que devuelve el Item propiedad o una de las bases de dicho tipo.The parameter to the Add method must be the same type as is returned from the Item property, or one of that type's bases. Para las clases que implementan ICollection, los valores que se va a serializar se recuperan desde el indizado Item propiedad, no mediante una llamada a GetEnumerator.For classes that implement ICollection, values to be serialized are retrieved from the indexed Item property, not by calling GetEnumerator.

Debe tener permiso para escribir en el directorio temporal (tal y como se define por la variable de entorno TEMP) deserializar un objeto.You must have permission to write to the temporary directory (as defined by the TEMP environment variable) to deserialize an object.

Ensamblados generados dinámicamenteDynamically Generated Assemblies

Para aumentar el rendimiento, la infraestructura de serialización XML genera dinámicamente los ensamblados para serializar y deserializar los tipos especificados.To increase performance, the XML serialization infrastructure dynamically generates assemblies to serialize and deserialize specified types. La infraestructura se encuentra y se vuelve a usar esos ensamblados.The infrastructure finds and reuses those assemblies. Este comportamiento se produce únicamente cuando se usan los constructores siguientes:This behavior occurs only when using the following constructors:

XmlSerializer.XmlSerializer(Type)

XmlSerializer.XmlSerializer(Type, String)

Si usa cualquiera de los otros constructores, varias versiones del mismo ensamblado se genera y no se descargan nunca, lo que produce una pérdida de memoria y un rendimiento deficiente.If you use any of the other constructors, multiple versions of the same assembly are generated and never unloaded, which results in a memory leak and poor performance. La solución más fácil es usar uno de los dos constructores mencionados anteriormente.The easiest solution is to use one of the previously mentioned two constructors. En caso contrario, se deben almacenar en caché los ensamblados en un Hashtable, como se muestra en el ejemplo siguiente.Otherwise, you must cache the assemblies in a Hashtable, as shown in the following example.

Hashtable serializers = new Hashtable();  

// Use the constructor that takes a type and XmlRootAttribute.  
XmlSerializer s = new XmlSerializer(typeof(MyClass), myRoot);  

// Implement a method named GenerateKey that creates unique keys   
// for each instance of the XmlSerializer. The code should take   
// into account all parameters passed to the XmlSerializer   
// constructor.  
object key = GenerateKey(typeof(MyClass), myRoot);  

// Check the local cache for a matching serializer.  
XmlSerializer ser = (XmlSerializer)serializers[key];  
if (ser == null)   
{  
    ser = new XmlSerializer(typeof(MyClass), myRoot);  
    // Cache the serializer.  
    serializers[key] = ser;  
}

// Use the serializer to serialize or deserialize.
Dim serializers As New Hashtable()  

' Use the constructor that takes a type and XmlRootAttribute.  
Dim s As New XmlSerializer(GetType([MyClass]), myRoot)  

' Implement a method named GenerateKey that creates unique keys   
' for each instance of the XmlSerializer. The code should take   
' into account all parameters passed to the XmlSerializer   
' constructor.  
Dim key As Object = GenerateKey(GetType([MyClass]), myRoot)  

' Check the local cache for a matching serializer.  
Dim ser As XmlSerializer = CType(serializers(key), XmlSerializer)  

If ser Is Nothing Then  
    ser = New XmlSerializer(GetType([MyClass]), myRoot)  
    ' Cache the serializer.  
    serializers(key) = ser  
End If  

' Use the serializer to serialize or deserialize.

Serialización de ArrayList y List genéricaSerialization of ArrayList and Generic List

El XmlSerializer no se puede serializar o deserializar lo siguiente:The XmlSerializer cannot serialize or deserialize the following:

Serialización de enumeraciones de Unsigned LongSerialization of Enumerations of Unsigned Long

El XmlSerializer no pueden crearse instancias para serializar una enumeración si se cumplen las condiciones siguientes: La enumeración es de tipo largo sin signo (ulong en C#) y la enumeración contiene cualquier miembro con un valor superior a + 9.223.372.036.854.775.807.The XmlSerializer cannot be instantiated to serialize an enumeration if the following conditions are true: The enumeration is of type unsigned long (ulong in C#) and the enumeration contains any member with a value larger than 9,223,372,036,854,775,807. Por ejemplo, la siguiente no se puede serializar.For example, the following cannot be serialized.

public enum LargeNumbers: ulong  
{  
    a = 9223372036854775808  
}  
// At runtime, the following code will fail.  
xmlSerializer mySerializer=new XmlSerializer(typeof(LargeNumbers));  

Marcado con el atributo Obsolete ya no se serializan los objetosObjects marked with the Obsolete Attribute no longer serialized

En el .NET Framework 3,5.NET Framework 3.5 el XmlSerializer clase ya no serializa los objetos que están marcados como [Obsolete].In the .NET Framework 3,5.NET Framework 3.5 the XmlSerializer class no longer serializes objects that are marked as [Obsolete].

Constructores

XmlSerializer() XmlSerializer() XmlSerializer() XmlSerializer()

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

XmlSerializer(Type) XmlSerializer(Type) XmlSerializer(Type) XmlSerializer(Type)

Inicializa una nueva instancia de la clase XmlSerializer que puede serializar objetos del tipo especificado en documentos XML y deserializar documentos XML en objetos del tipo especificado.Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into objects of the specified type.

XmlSerializer(Type, String) XmlSerializer(Type, String) XmlSerializer(Type, String) XmlSerializer(Type, String)

Inicializa una nueva instancia de la clase XmlSerializer que puede serializar objetos del tipo especificado en documentos XML y deserializar documentos XML en objetos del tipo especificado.Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into objects of the specified type. Especifica el espacio de nombres predeterminado para todos los elementos XML.Specifies the default namespace for all the XML elements.

XmlSerializer(Type, Type[]) XmlSerializer(Type, Type[]) XmlSerializer(Type, Type[]) XmlSerializer(Type, Type[])

Inicializa una nueva instancia de la clase XmlSerializer que puede serializar objetos del tipo especificado en documentos XML y deserializar documentos XML en objetos del tipo especificado.Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into object of a specified type. Si una propiedad o un campo devuelve una matriz, el parámetro extraTypes especifica aquellos objetos que pueden insertarse en la matriz.If a property or field returns an array, the extraTypes parameter specifies objects that can be inserted into the array.

XmlSerializer(Type, XmlAttributeOverrides) XmlSerializer(Type, XmlAttributeOverrides) XmlSerializer(Type, XmlAttributeOverrides) XmlSerializer(Type, XmlAttributeOverrides)

Inicializa una nueva instancia de la clase XmlSerializer que puede serializar objetos del tipo especificado en documentos XML y deserializar documentos XML en objetos del tipo especificado.Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into objects of the specified type. Cada objeto que se ha de serializar también puede contener instancias de clases, que esta sobrecarga puede reemplazar con otras clases.Each object to be serialized can itself contain instances of classes, which this overload can override with other classes.

XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String) XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String) XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String) XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String)

Inicializa una nueva instancia de la clase XmlSerializer que puede serializar objetos del tipo Object en instancias de documentos XML y deserializar instancias de documentos XML en objetos del tipo Object.Initializes a new instance of the XmlSerializer class that can serialize objects of type Object into XML document instances, and deserialize XML document instances into objects of type Object. Cada objeto que se ha de serializar también puede contener instancias de clases, que esta sobrecarga reemplaza con otras clases.Each object to be serialized can itself contain instances of classes, which this overload overrides with other classes. Esta sobrecarga especifica asimismo el espacio de nombres predeterminado para todos los elementos XML, así como la clase que se ha de utilizar como elemento raíz XML.This overload also specifies the default namespace for all the XML elements and the class to use as the XML root element.

XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String) XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String) XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String) XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String)

Inicializa una nueva instancia de la clase XmlSerializer que puede serializar objetos del tipo Object en instancias de documentos XML y deserializar instancias de documentos XML en objetos del tipo Object.Initializes a new instance of the XmlSerializer class that can serialize objects of type Object into XML document instances, and deserialize XML document instances into objects of type Object. Cada objeto que se ha de serializar también puede contener instancias de clases, que esta sobrecarga reemplaza con otras clases.Each object to be serialized can itself contain instances of classes, which this overload overrides with other classes. Esta sobrecarga especifica asimismo el espacio de nombres predeterminado para todos los elementos XML, así como la clase que se ha de utilizar como elemento raíz XML.This overload also specifies the default namespace for all the XML elements and the class to use as the XML root element.

XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String, Evidence) XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String, Evidence) XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String, Evidence) XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String, Evidence)

Inicializa una nueva instancia de la clase XmlSerializer que puede serializar objetos del tipo especificado en instancias de documentos XML y deserializar instancias de documentos XML en objetos del tipo especificado.Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML document instances, and deserialize XML document instances into objects of the specified type. Esta sobrecarga permite proporcionar otros tipos que se pueden encontrar durante una operación de serialización o deserialización, así como un espacio de nombres predeterminado para todos los elementos XML, la clase que se debe utilizar como elemento raíz de XML, su ubicación y las credenciales requerida para el acceso.This overload allows you to supply other types that can be encountered during a serialization or deserialization operation, as well as a default namespace for all XML elements, the class to use as the XML root element, its location, and credentials required for access.

XmlSerializer(Type, XmlRootAttribute) XmlSerializer(Type, XmlRootAttribute) XmlSerializer(Type, XmlRootAttribute) XmlSerializer(Type, XmlRootAttribute)

Inicializa una nueva instancia de la clase XmlSerializer que puede serializar objetos del tipo especificado en documentos XML y deserializar un documento XML en un objeto del tipo especificado.Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize an XML document into object of the specified type. Especifica también la clase que se utilizará como elemento raíz XML.It also specifies the class to use as the XML root element.

XmlSerializer(XmlTypeMapping) XmlSerializer(XmlTypeMapping) XmlSerializer(XmlTypeMapping) XmlSerializer(XmlTypeMapping)

Inicializa una instancia de la clase XmlSerializer utilizando un objeto que asigna un tipo a otro.Initializes an instance of the XmlSerializer class using an object that maps one type to another.

Métodos

CanDeserialize(XmlReader) CanDeserialize(XmlReader) CanDeserialize(XmlReader) CanDeserialize(XmlReader)

Obtiene un valor que indica si este XmlSerializer puede deserializar un documento XML especificado.Gets a value that indicates whether this XmlSerializer can deserialize a specified XML document.

CreateReader() CreateReader() CreateReader() CreateReader()

Devuelve un objeto utilizado para leer el documento XML que se va a serializar.Returns an object used to read the XML document to be serialized.

CreateWriter() CreateWriter() CreateWriter() CreateWriter()

Cuando se reemplaza en una clase derivada, devuelve un sistema de escritura para serializar el objeto.When overridden in a derived class, returns a writer used to serialize the object.

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

Deserializa un documento XML que contiene el Stream especificado.Deserializes the XML document contained by the specified Stream.

Deserialize(TextReader) Deserialize(TextReader) Deserialize(TextReader) Deserialize(TextReader)

Deserializa un documento XML que contiene el TextReader especificado.Deserializes the XML document contained by the specified TextReader.

Deserialize(XmlReader) Deserialize(XmlReader) Deserialize(XmlReader) Deserialize(XmlReader)

Deserializa un documento XML que contiene el XmlReader especificado.Deserializes the XML document contained by the specified XmlReader.

Deserialize(XmlReader, String) Deserialize(XmlReader, String) Deserialize(XmlReader, String) Deserialize(XmlReader, String)

Deserializa un documento XML que contiene el XmlReader especificado y el estilo de codificación.Deserializes the XML document contained by the specified XmlReader and encoding style.

Deserialize(XmlReader, String, XmlDeserializationEvents) Deserialize(XmlReader, String, XmlDeserializationEvents) Deserialize(XmlReader, String, XmlDeserializationEvents) Deserialize(XmlReader, String, XmlDeserializationEvents)

Deserializa el objeto utilizando los datos que se encuentran en el XmlReader especificado.Deserializes the object using the data contained by the specified XmlReader.

Deserialize(XmlReader, XmlDeserializationEvents) Deserialize(XmlReader, XmlDeserializationEvents) Deserialize(XmlReader, XmlDeserializationEvents) Deserialize(XmlReader, XmlDeserializationEvents)

Deserializa un documento XML que se encuentra en el XmlReader especificado y permite reemplazar los eventos que se producen durante la deserialización.Deserializes an XML document contained by the specified XmlReader and allows the overriding of events that occur during deserialization.

Deserialize(XmlSerializationReader) Deserialize(XmlSerializationReader) Deserialize(XmlSerializationReader) Deserialize(XmlSerializationReader)

Deserializa un documento XML que contiene el XmlSerializationReader especificado.Deserializes the XML document contained by the specified XmlSerializationReader.

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)
FromMappings(XmlMapping[]) FromMappings(XmlMapping[]) FromMappings(XmlMapping[]) FromMappings(XmlMapping[])

Devuelve una matriz de objetos XmlSerializer creada a partir de una matriz de objetos XmlTypeMapping.Returns an array of XmlSerializer objects created from an array of XmlTypeMapping objects.

FromMappings(XmlMapping[], Evidence) FromMappings(XmlMapping[], Evidence) FromMappings(XmlMapping[], Evidence) FromMappings(XmlMapping[], Evidence)

Devuelve una instancia de la clase XmlSerializer creada a partir de las asignaciones de un tipo de XML a otro.Returns an instance of the XmlSerializer class created from mappings of one XML type to another.

FromMappings(XmlMapping[], Type) FromMappings(XmlMapping[], Type) FromMappings(XmlMapping[], Type) FromMappings(XmlMapping[], Type)

Devuelve una instancia de la clase XmlSerializer a partir de las asignaciones especificadas.Returns an instance of the XmlSerializer class from the specified mappings.

FromTypes(Type[]) FromTypes(Type[]) FromTypes(Type[]) FromTypes(Type[])

Devuelve una matriz de objetos XmlSerializer creada a partir de una matriz de tipos.Returns an array of XmlSerializer objects created from an array of types.

GenerateSerializer(Type[], XmlMapping[]) GenerateSerializer(Type[], XmlMapping[]) GenerateSerializer(Type[], XmlMapping[]) GenerateSerializer(Type[], XmlMapping[])

Devuelve un ensamblado que contiene los serializadores personalizados utilizados para serializar o deserializar los tipos especificados, utilizando las asignaciones especificadas.Returns an assembly that contains custom-made serializers used to serialize or deserialize the specified type or types, using the specified mappings.

GenerateSerializer(Type[], XmlMapping[], CompilerParameters) GenerateSerializer(Type[], XmlMapping[], CompilerParameters) GenerateSerializer(Type[], XmlMapping[], CompilerParameters) GenerateSerializer(Type[], XmlMapping[], CompilerParameters)

Devuelve un ensamblado que contiene los serializadores personalizados utilizados para serializar o deserializar los tipos especificados, utilizando las asignaciones especificadas y las configuraciones y opciones del compilador.Returns an assembly that contains custom-made serializers used to serialize or deserialize the specified type or types, using the specified mappings and compiler settings and options.

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)
GetXmlSerializerAssemblyName(Type) GetXmlSerializerAssemblyName(Type) GetXmlSerializerAssemblyName(Type) GetXmlSerializerAssemblyName(Type)

Devuelve el nombre del ensamblado que contiene una o más versiones de XmlSerializer creado especialmente para serializar o deserializar el tipo especificado.Returns the name of the assembly that contains one or more versions of the XmlSerializer especially created to serialize or deserialize the specified type.

GetXmlSerializerAssemblyName(Type, String) GetXmlSerializerAssemblyName(Type, String) GetXmlSerializerAssemblyName(Type, String) GetXmlSerializerAssemblyName(Type, String)

Devuelve el nombre del ensamblado que contiene el serializador para el tipo especificado en el espacio de nombres especificado.Returns the name of the assembly that contains the serializer for the specified type in the specified namespace.

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

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

(Inherited from Object)
Serialize(Object, XmlSerializationWriter) Serialize(Object, XmlSerializationWriter) Serialize(Object, XmlSerializationWriter) Serialize(Object, XmlSerializationWriter)

Serializa el Object especificado y escribe el documento XML en un archivo utilizando el XmlSerializationWriter especificado.Serializes the specified Object and writes the XML document to a file using the specified XmlSerializationWriter.

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

Serializa el Object especificado y escribe el documento XML en un archivo utilizando el Stream especificado.Serializes the specified Object and writes the XML document to a file using the specified Stream.

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

Serializa el Object especificado y escribe el documento XML en un archivo utilizando el Stream especificado, que hace referencia a los espacios de nombres especificados.Serializes the specified Object and writes the XML document to a file using the specified Stream that references the specified namespaces.

Serialize(TextWriter, Object) Serialize(TextWriter, Object) Serialize(TextWriter, Object) Serialize(TextWriter, Object)

Serializa el Object especificado y escribe el documento XML en un archivo utilizando el TextWriter especificado.Serializes the specified Object and writes the XML document to a file using the specified TextWriter.

Serialize(TextWriter, Object, XmlSerializerNamespaces) Serialize(TextWriter, Object, XmlSerializerNamespaces) Serialize(TextWriter, Object, XmlSerializerNamespaces) Serialize(TextWriter, Object, XmlSerializerNamespaces)

Serializa el objeto Object especificado, escribe el documento XML en un archivo utilizando el objeto TextWriter especificado y hace referencia a los espacios de nombres especificados.Serializes the specified Object and writes the XML document to a file using the specified TextWriter and references the specified namespaces.

Serialize(XmlWriter, Object) Serialize(XmlWriter, Object) Serialize(XmlWriter, Object) Serialize(XmlWriter, Object)

Serializa el Object especificado y escribe el documento XML en un archivo utilizando el XmlWriter especificado.Serializes the specified Object and writes the XML document to a file using the specified XmlWriter.

Serialize(XmlWriter, Object, XmlSerializerNamespaces) Serialize(XmlWriter, Object, XmlSerializerNamespaces) Serialize(XmlWriter, Object, XmlSerializerNamespaces) Serialize(XmlWriter, Object, XmlSerializerNamespaces)

Serializa el objeto Object especificado, escribe el documento XML en un archivo utilizando el objeto XmlWriter especificado y hace referencia a los espacios de nombres especificados.Serializes the specified Object and writes the XML document to a file using the specified XmlWriter and references the specified namespaces.

Serialize(XmlWriter, Object, XmlSerializerNamespaces, String) Serialize(XmlWriter, Object, XmlSerializerNamespaces, String) Serialize(XmlWriter, Object, XmlSerializerNamespaces, String) Serialize(XmlWriter, Object, XmlSerializerNamespaces, String)

Serializa el objeto especificado, escribe el documento XML en un archivo utilizando el XmlWriter especificado y hace referencia a los espacios de nombres especificados y al estilo de codificación.Serializes the specified object and writes the XML document to a file using the specified XmlWriter and references the specified namespaces and encoding style.

Serialize(XmlWriter, Object, XmlSerializerNamespaces, String, String) Serialize(XmlWriter, Object, XmlSerializerNamespaces, String, String) Serialize(XmlWriter, Object, XmlSerializerNamespaces, String, String) Serialize(XmlWriter, Object, XmlSerializerNamespaces, String, String)

Serializa el Object especificado y escribe el documento XML en un archivo mediante el XmlWriter especificado, así como los espacios de nombres y la codificación especificados.Serializes the specified Object and writes the XML document to a file using the specified XmlWriter, XML namespaces, and encoding.

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

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

(Inherited from Object)

Eventos

UnknownAttribute UnknownAttribute UnknownAttribute UnknownAttribute

Se produce cuando XmlSerializer detecta un atributo XML de tipo desconocido durante la deserialización.Occurs when the XmlSerializer encounters an XML attribute of unknown type during deserialization.

UnknownElement UnknownElement UnknownElement UnknownElement

Se produce cuando XmlSerializer detecta un elemento XML de tipo desconocido durante la deserialización.Occurs when the XmlSerializer encounters an XML element of unknown type during deserialization.

UnknownNode UnknownNode UnknownNode UnknownNode

Se produce cuando XmlSerializer detecta un nodo XML de tipo desconocido durante la deserialización.Occurs when the XmlSerializer encounters an XML node of unknown type during deserialization.

UnreferencedObject UnreferencedObject UnreferencedObject UnreferencedObject

Se produce durante la deserialización de una secuencia XML con codificación SOAP, cuando XmlSerializer encuentra un tipo reconocido que no se utiliza o al que no se hace referencia.Occurs during deserialization of a SOAP-encoded XML stream, when the XmlSerializer encounters a recognized type that is not used or is unreferenced.

Se aplica a

Seguridad para subprocesos

Este tipo es seguro para la ejecución de subprocesos.This type is thread safe.

Consulte también: