XmlSerializer Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Serializa e desserializa objetos em e a partir de documentos XML. Permite-te 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 seguinte contém duas classes principais: PurchaseOrder e Test. A PurchaseOrder aula 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
Observações
Para mais informações sobre esta API, consulte Observações suplementares da API para XmlSerializer.
Construtores
| Name | Description |
|---|---|
| XmlSerializer() |
Inicializa uma nova instância da XmlSerializer classe. |
| 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 objetos de um tipo especificado. Se uma propriedade ou campo devolver um array, o |
| 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 documentos XML em objetos do tipo especificado. Esta 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 usar como elemento raiz XML, a sua localização e credenciais necessárias para o 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 documentos XML e desserializar instâncias de documentos XML em objetos do tipo Object. Cada objeto a serializar pode conter instâncias de classes, que esta sobrecarga sobrepõe com outras classes. Esta sobrecarga também especifica o namespace padrão para todos os elementos XML e a classe a usar como 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 documentos XML e desserializar instâncias de documentos XML em objetos do tipo Object. Cada objeto a serializar pode conter instâncias de classes, que esta sobrecarga sobrepõe com outras classes. Esta sobrecarga também especifica o namespace padrão para todos os elementos XML e a classe a usar como 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 serializar pode conter instâncias de classes, que esta sobrecarga pode sobrepor 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 em objeto do tipo especificado. Também especifica a classe a usar como 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
| Name | Description |
|---|---|
| CanDeserialize(XmlReader) |
Obtém um valor que indica se isto XmlSerializer pode desserializar um documento XML especificado. |
| CreateReader() |
Devolve um objeto usado para ler o documento XML a ser serializado. |
| CreateWriter() |
Quando sobreposto numa classe derivada, devolve um escritor 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 pelo estilo especificado XmlReader e de codificação. |
| Deserialize(XmlReader, XmlDeserializationEvents) |
Desserializa um documento XML contido pelo especificado XmlReader e permite a sobreposiçã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.
Devolve uma instância da XmlSerializer classe criada a partir de mapeamentos de um tipo XML para outro. |
| FromMappings(XmlMapping[], Type) |
Devolve uma instância da XmlSerializer classe a partir dos mapeamentos especificados. |
| FromMappings(XmlMapping[]) |
Devolve um array de XmlSerializer objetos criado a partir de um array de XmlTypeMapping objetos. |
| FromTypes(Type[]) |
Devolve um array de XmlSerializer objetos criados a partir de um array de tipos. |
| GenerateSerializer(Type[], XmlMapping[], CompilerParameters) |
Devolve um assembly que contém serializadores personalizados usados para serializar ou desserializar o tipo ou tipos especificados, usando os mapeamentos e definições e opções do compilador especificados. |
| GenerateSerializer(Type[], XmlMapping[]) |
Devolve um conjunto que contém serializadores personalizados usados para serializar ou desserializar o tipo ou tipos especificados, usando os mapeamentos especificados. |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| GetXmlSerializerAssemblyName(Type, String) |
Devolve o nome do assembly que contém o serializador para o tipo especificado no espaço de nomes especificado. |
| GetXmlSerializerAssemblyName(Type) |
Devolve o nome do assembly que contém uma ou mais versões do XmlSerializer especialmente criadas para serializar ou desserializar o tipo especificado. |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| Serialize(Object, XmlSerializationWriter) |
Serializa o especificado Object e escreve o documento XML num ficheiro usando o ficheiro especificado XmlSerializationWriter. |
| Serialize(Stream, Object, XmlSerializerNamespaces) |
Serializa o especificado Object e escreve o documento XML num ficheiro usando o especificado Stream que faz referência aos espaços de nomes especificados. |
| Serialize(Stream, Object) |
Serializa o especificado Object e escreve o documento XML num ficheiro usando o ficheiro especificado Stream. |
| Serialize(TextWriter, Object, XmlSerializerNamespaces) |
Serializa o especificado Object e escreve o documento XML num ficheiro usando o especificado TextWriter e faz referência aos espaços de nomes especificados. |
| Serialize(TextWriter, Object) |
Serializa o especificado Object e escreve o documento XML num ficheiro usando o ficheiro especificado TextWriter. |
| Serialize(XmlWriter, Object, XmlSerializerNamespaces, String, String) |
Serializa o especificado Object e escreve o documento XML num ficheiro usando os espaços de nomes XML especificados XmlWritere a codificação. |
| Serialize(XmlWriter, Object, XmlSerializerNamespaces, String) |
Serializa o objeto especificado e escreve o documento XML num ficheiro usando o especificado XmlWriter e faz referência aos namespaces e estilo de codificação especificados. |
| Serialize(XmlWriter, Object, XmlSerializerNamespaces) |
Serializa o especificado Object e escreve o documento XML num ficheiro usando o especificado XmlWriter e faz referência aos espaços de nomes especificados. |
| Serialize(XmlWriter, Object) |
Serializa o especificado Object e escreve o documento XML num ficheiro usando o ficheiro especificado XmlWriter. |
| ToString() |
Devolve uma cadeia que representa o objeto atual. (Herdado de Object) |
evento
| Name | Description |
|---|---|
| UnknownAttribute |
Ocorre quando encontra XmlSerializer um atributo XML de tipo desconhecido durante a desserialização. |
| UnknownElement |
Ocorre quando encontra XmlSerializer um elemento XML de tipo desconhecido durante a desserialização. |
| UnknownNode |
Ocorre quando encontra XmlSerializer um nó XML de tipo desconhecido durante a desserialização. |
| UnreferencedObject |
Ocorre durante a desserialização de um fluxo XML codificado em SOAP, quando encontra XmlSerializer um tipo reconhecido que não é utilizado ou não está referenciado. |
Aplica-se a
Segurança de Thread
Este tipo é seguro para fios.
Ver também
- XmlAttributeOverrides
- XmlAttributes
- XmlText
- Apresentando a serialização XML
- Como: Especificar um nome de elemento alternativo para um fluxo XML
- Controlando a serialização XML usando atributos
- Exemplos de serialização XML
- Ferramenta de definição de esquema XML (Xsd.exe)
- Como: Controlar a Serialização de Classes Derivadas
- <Elemento dateTimeSerialization>
- <xmlSerializer> Element