XmlSerializer Classe

Definição

Serializa e desserializa objetos de e para documentos XML. Permite XmlSerializer controlar como os objetos são codificados em XML.

public ref class XmlSerializer
public class XmlSerializer
type XmlSerializer = class
Public Class XmlSerializer
Herança
XmlSerializer

Exemplos

O exemplo a seguir contém duas classes principais: PurchaseOrder e Test. A PurchaseOrder classe contém informações sobre uma única compra. A Test classe contém os métodos que criam a ordem de compra e que leem a ordem de compra criada.

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.Xml
Imports System.Xml.Serialization
Imports 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 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


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


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
End Class


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
    
   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
    
   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
    
    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
        
    Private Sub serializer_UnknownNode(sender As Object, e As XmlNodeEventArgs)
        Console.WriteLine(("Unknown Node:" & e.Name & ControlChars.Tab & e.Text))
    End Sub
    
    
    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
End Class

Comentários

Para obter mais informações sobre essa API, consulte comentários de API Suplementar para XmlSerializer.

Construtores

Nome Description
XmlSerializer()

Inicializa uma nova instância da classe XmlSerializer.

XmlSerializer(Type, String)

Inicializa uma nova instância da XmlSerializer classe que pode serializar objetos do tipo especificado em documentos XML e desserializar documentos XML em objetos do tipo especificado. Especifica o namespace padrão para todos os elementos XML.

XmlSerializer(Type, Type[])

Inicializa uma nova instância da XmlSerializer classe que pode serializar objetos do tipo especificado em documentos XML e desserializar documentos XML em um objeto de um tipo especificado. Se uma propriedade ou campo retornar uma matriz, o extraTypes parâmetro especifica os objetos que podem ser inseridos na matriz.

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

Inicializa uma nova instância da XmlSerializer classe que pode serializar objetos do tipo especificado em instâncias de documento XML e desserializar instâncias de documento XML em objetos do tipo especificado. Essa sobrecarga permite fornecer outros tipos que podem ser encontrados durante uma operação de serialização ou desserialização, bem como um namespace padrão para todos os elementos XML, a classe a ser usada como o elemento raiz XML, sua localização e credenciais necessárias para acesso.

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

Inicializa uma nova instância da XmlSerializer classe que pode serializar objetos do tipo Object em instâncias de documento XML e desserializar instâncias de documento XML em objetos do tipo Object. Cada objeto a ser serializado pode conter instâncias de classes, que essa sobrecarga substitui com outras classes. Essa sobrecarga também especifica o namespace padrão para todos os elementos XML e a classe a ser usada como o elemento raiz XML.

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

Inicializa uma nova instância da XmlSerializer classe que pode serializar objetos do tipo Object em instâncias de documento XML e desserializar instâncias de documento XML em objetos do tipo Object. Cada objeto a ser serializado pode conter instâncias de classes, que essa sobrecarga substitui com outras classes. Essa sobrecarga também especifica o namespace padrão para todos os elementos XML e a classe a ser usada como o elemento raiz XML.

XmlSerializer(Type, XmlAttributeOverrides)

Inicializa uma nova instância da XmlSerializer classe que pode serializar objetos do tipo especificado em documentos XML e desserializar documentos XML em objetos do tipo especificado. Cada objeto a ser serializado pode conter instâncias de classes, que essa sobrecarga pode substituir com outras classes.

XmlSerializer(Type, XmlRootAttribute)

Inicializa uma nova instância da XmlSerializer classe que pode serializar objetos do tipo especificado em documentos XML e desserializar um documento XML no objeto do tipo especificado. Ele também especifica a classe a ser usada como o elemento raiz XML.

XmlSerializer(Type)

Inicializa uma nova instância da XmlSerializer classe que pode serializar objetos do tipo especificado em documentos XML e desserializar documentos XML em objetos do tipo especificado.

XmlSerializer(XmlTypeMapping)

Inicializa uma instância da XmlSerializer classe usando um objeto que mapeia um tipo para outro.

Métodos

Nome Description
CanDeserialize(XmlReader)

Obtém um valor que indica se isso XmlSerializer pode desserializar um documento XML especificado.

CreateReader()

Retorna um objeto usado para ler o documento XML a ser serializado.

CreateWriter()

Quando substituído em uma classe derivada, retorna um gravador usado para serializar o objeto.

Deserialize(Stream)

Desserializa o documento XML contido pelo especificado Stream.

Deserialize(TextReader)

Desserializa o documento XML contido pelo especificado TextReader.

Deserialize(XmlReader, String, XmlDeserializationEvents)

Desserializa o objeto usando os dados contidos pelo especificado XmlReader.

Deserialize(XmlReader, String)

Desserializa o documento XML contido no estilo especificado XmlReader e de codificação.

Deserialize(XmlReader, XmlDeserializationEvents)

Desserializa um documento XML contido pelo especificado XmlReader e permite a substituição de eventos que ocorrem durante a desserialização.

Deserialize(XmlReader)

Desserializa o documento XML contido pelo especificado XmlReader.

Deserialize(XmlSerializationReader)

Desserializa o documento XML contido pelo especificado XmlSerializationReader.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
FromMappings(XmlMapping[], Evidence)
Obsoleto.

Retorna uma instância da classe criada a XmlSerializer partir de mapeamentos de um tipo XML para outro.

FromMappings(XmlMapping[], Type)

Retorna uma instância da XmlSerializer classe dos mapeamentos especificados.

FromMappings(XmlMapping[])

Retorna uma matriz de XmlSerializer objetos criados a partir de uma matriz de XmlTypeMapping objetos.

FromTypes(Type[])

Retorna uma matriz de XmlSerializer objetos criados a partir de uma matriz de tipos.

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

Retorna um assembly que contém serializadores personalizados usados para serializar ou desserializar o tipo ou tipos especificados, usando os mapeamentos especificados e as configurações e opções do compilador.

GenerateSerializer(Type[], XmlMapping[])

Retorna um assembly que contém serializadores personalizados usados para serializar ou desserializar o tipo ou tipos especificados, usando os mapeamentos especificados.

GetHashCode()

Serve como a função hash predefinida.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
GetXmlSerializerAssemblyName(Type, String)

Retorna o nome do assembly que contém o serializador para o tipo especificado no namespace especificado.

GetXmlSerializerAssemblyName(Type)

Retorna o nome do assembly que contém uma ou mais versões das XmlSerializer especialmente criadas para serializar ou desserializar o tipo especificado.

MemberwiseClone()

Cria uma cópia superficial do Objectatual.

(Herdado de Object)
Serialize(Object, XmlSerializationWriter)

Serializa o documento XML especificado Object e grava o documento XML em um arquivo usando o especificado XmlSerializationWriter.

Serialize(Stream, Object, XmlSerializerNamespaces)

Serializa o documento XML especificado Object e grava em um arquivo usando o especificado Stream que faz referência aos namespaces especificados.

Serialize(Stream, Object)

Serializa o documento XML especificado Object e grava o documento XML em um arquivo usando o especificado Stream.

Serialize(TextWriter, Object, XmlSerializerNamespaces)

Serializa o documento XML especificado Object e grava o documento XML em um arquivo usando os namespaces especificados TextWriter e faz referência aos namespaces especificados.

Serialize(TextWriter, Object)

Serializa o documento XML especificado Object e grava o documento XML em um arquivo usando o especificado TextWriter.

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

Serializa o documento XML especificado Object e grava o documento XML em um arquivo usando os namespaces XML e a codificação especificados XmlWriter.

Serialize(XmlWriter, Object, XmlSerializerNamespaces, String)

Serializa o objeto especificado e grava o documento XML em um arquivo usando o especificado XmlWriter e faz referência aos namespaces especificados e ao estilo de codificação.

Serialize(XmlWriter, Object, XmlSerializerNamespaces)

Serializa o documento XML especificado Object e grava o documento XML em um arquivo usando os namespaces especificados XmlWriter e faz referência aos namespaces especificados.

Serialize(XmlWriter, Object)

Serializa o documento XML especificado Object e grava o documento XML em um arquivo usando o especificado XmlWriter.

ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Eventos

Nome Description
UnknownAttribute

Ocorre quando o XmlSerializer atributo XML encontra um tipo desconhecido durante a desserialização.

UnknownElement

Ocorre quando o XmlSerializer elemento XML encontra um elemento XML de tipo desconhecido durante a desserialização.

UnknownNode

Ocorre quando o XmlSerializer nó XML encontra um nó XML de tipo desconhecido durante a desserialização.

UnreferencedObject

Ocorre durante a desserialização de um fluxo XML codificado em SOAP, quando o XmlSerializer encontro de um tipo reconhecido que não é usado ou não é referenciado.

Aplica-se a

Acesso thread-safe

Esse tipo é thread safe.

Confira também