XmlAttributeOverrides 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.
Permite sobrepor atributos de propriedade, campo e classe quando usas o XmlSerializer para serializar ou desserializar um objeto.
public ref class XmlAttributeOverrides
public class XmlAttributeOverrides
type XmlAttributeOverrides = class
Public Class XmlAttributeOverrides
- Herança
-
XmlAttributeOverrides
Exemplos
O exemplo seguinte serializa uma classe chamada Orchestra, que contém um único campo nomeado Instruments que devolve um array de Instrument objetos. Uma segunda classe chamada Brass herda da Instrument classe. O exemplo utiliza uma instância da XmlAttributeOverrides classe para sobrescrever o Instrument campo, permitindo que o campo aceite Brass objetos.
using System;
using System.IO;
using System.Xml.Serialization;
public class Orchestra
{
public Instrument[] Instruments;
}
public class Instrument
{
public string Name;
}
public class Brass:Instrument
{
public bool IsValved;
}
public class Run
{
public static void Main()
{
Run test = new Run();
test.SerializeObject("Override.xml");
test.DeserializeObject("Override.xml");
}
public void SerializeObject(string filename)
{
/* Each overridden field, property, or type requires
an XmlAttributes object. */
XmlAttributes attrs = new XmlAttributes();
/* Create an XmlElementAttribute to override the
field that returns Instrument objects. The overridden field
returns Brass objects instead. */
XmlElementAttribute attr = new XmlElementAttribute();
attr.ElementName = "Brass";
attr.Type = typeof(Brass);
// Add the element to the collection of elements.
attrs.XmlElements.Add(attr);
// Create the XmlAttributeOverrides object.
XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();
/* Add the type of the class that contains the overridden
member and the XmlAttributes to override it with to the
XmlAttributeOverrides object. */
attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);
// Create the XmlSerializer using the XmlAttributeOverrides.
XmlSerializer s =
new XmlSerializer(typeof(Orchestra), attrOverrides);
// Writing the file requires a TextWriter.
TextWriter writer = new StreamWriter(filename);
// Create the object that will be serialized.
Orchestra band = new Orchestra();
// Create an object of the derived type.
Brass i = new Brass();
i.Name = "Trumpet";
i.IsValved = true;
Instrument[] myInstruments = {i};
band.Instruments = myInstruments;
// Serialize the object.
s.Serialize(writer,band);
writer.Close();
}
public void DeserializeObject(string filename)
{
XmlAttributeOverrides attrOverrides =
new XmlAttributeOverrides();
XmlAttributes attrs = new XmlAttributes();
// Create an XmlElementAttribute to override the Instrument.
XmlElementAttribute attr = new XmlElementAttribute();
attr.ElementName = "Brass";
attr.Type = typeof(Brass);
// Add the XmlElementAttribute to the collection of objects.
attrs.XmlElements.Add(attr);
attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);
// Create the XmlSerializer using the XmlAttributeOverrides.
XmlSerializer s =
new XmlSerializer(typeof(Orchestra), attrOverrides);
FileStream fs = new FileStream(filename, FileMode.Open);
Orchestra band = (Orchestra) s.Deserialize(fs);
Console.WriteLine("Brass:");
/* The difference between deserializing the overridden
XML document and serializing it is this: To read the derived
object values, you must declare an object of the derived type
(Brass), and cast the Instrument instance to it. */
Brass b;
foreach(Instrument i in band.Instruments)
{
b = (Brass)i;
Console.WriteLine(
b.Name + "\n" +
b.IsValved);
}
}
}
Option Explicit
Option Strict
Imports System.IO
Imports System.Xml.Serialization
Public Class Orchestra
Public Instruments() As Instrument
End Class
Public Class Instrument
Public Name As String
End Class
Public Class Brass
Inherits Instrument
Public IsValved As Boolean
End Class
Public Class Run
Public Shared Sub Main()
Dim test As New Run()
test.SerializeObject("Override.xml")
test.DeserializeObject("Override.xml")
End Sub
Public Sub SerializeObject(ByVal filename As String)
' Each overridden field, property, or type requires
' an XmlAttributes object.
Dim attrs As New XmlAttributes()
' Create an XmlElementAttribute to override the
' field that returns Instrument objects. The overridden field
' returns Brass objects instead.
Dim attr As New XmlElementAttribute()
attr.ElementName = "Brass"
attr.Type = GetType(Brass)
' Add the element to the collection of elements.
attrs.XmlElements.Add(attr)
' Create the XmlAttributeOverrides object.
Dim attrOverrides As New XmlAttributeOverrides()
' Add the type of the class that contains the overridden
' member and the XmlAttributes to override it with to the
' XmlAttributeOverrides object.
attrOverrides.Add(GetType(Orchestra), "Instruments", attrs)
' Create the XmlSerializer using the XmlAttributeOverrides.
Dim s As New XmlSerializer(GetType(Orchestra), attrOverrides)
' Writing the file requires a TextWriter.
Dim writer As New StreamWriter(filename)
' Create the object that will be serialized.
Dim band As New Orchestra()
' Create an object of the derived type.
Dim i As New Brass()
i.Name = "Trumpet"
i.IsValved = True
Dim myInstruments() As Instrument = {i}
band.Instruments = myInstruments
' Serialize the object.
s.Serialize(writer, band)
writer.Close()
End Sub
Public Sub DeserializeObject(filename As String)
Dim attrOverrides As New XmlAttributeOverrides()
Dim attrs As New XmlAttributes()
' Create an XmlElementAttribute to override the Instrument.
Dim attr As New XmlElementAttribute()
attr.ElementName = "Brass"
attr.Type = GetType(Brass)
' Add the XmlElementAttribute to the collection of objects.
attrs.XmlElements.Add(attr)
attrOverrides.Add(GetType(Orchestra), "Instruments", attrs)
' Create the XmlSerializer using the XmlAttributeOverrides.
Dim s As New XmlSerializer(GetType(Orchestra), attrOverrides)
Dim fs As New FileStream(filename, FileMode.Open)
Dim band As Orchestra = CType(s.Deserialize(fs), Orchestra)
Console.WriteLine("Brass:")
' The difference between deserializing the overridden
' XML document and serializing it is this: To read the derived
' object values, you must declare an object of the derived type
' (Brass), and cast the Instrument instance to it.
Dim b As Brass
Dim i As Instrument
For Each i In band.Instruments
b = CType(i, Brass)
Console.WriteLine(b.Name & ControlChars.Cr & b.IsValved)
Next i
End Sub
End Class
Observações
Permite XmlAttributeOverrides que o XmlSerializer substitua a forma padrão de serializar um conjunto de objetos. A sobreposição da serialização desta forma tem duas utilidades: primeiro, pode controlar e aumentar a serialização de objetos encontrados numa DLL — mesmo que não tenha acesso à fonte; Segundo, podes criar um conjunto de classes serializáveis, mas serializar os objetos de várias formas. Por exemplo, em vez de serializar membros de uma instância de classe como elementos XML, pode serializá-los como atributos XML, resultando num documento mais eficiente de transportar.
Depois de criar um XmlAttributeOverrides objeto, passa-o como argumento ao XmlSerializer construtor. O resultado XmlSerializer utiliza os dados contidos pelo XmlAttributeOverrides para sobrepor atributos que controlam como os objetos são serializados. Para isso, o XmlAttributeOverrides contém uma coleção dos tipos de objetos que são sobrepostos, bem como um XmlAttributes objeto associado a cada tipo de objeto sobreposto. O XmlAttributes próprio objeto contém um conjunto apropriado de objetos de atributo que controlam como cada campo, propriedade ou classe é serializado.
O processo para criar e usar um XmlAttributeOverrides objeto é o seguinte:
Crie um XmlAttributes objeto.
Crie um objeto de atributo apropriado ao objeto que está a ser sobreposto. Por exemplo, para sobrescrever um campo ou propriedade, crie um XmlElementAttribute, usando o novo tipo derivado. Podes opcionalmente atribuir um novo ElementName, ou Namespace que sobreponha o nome do atributo ou namespace da classe base.
Adicione o objeto de atributo à propriedade ou coleção apropriada XmlAttributes . Por exemplo, adicionaria o XmlElementAttribute à XmlElements coleção do XmlAttributes objeto, especificando o nome do membro que está a ser sobreposto.
Crie um XmlAttributeOverrides objeto.
Usando o Add método, adiciona o XmlAttributes objeto ao XmlAttributeOverrides objeto. Se o objeto a ser sobreposto for um XmlRootAttribute ou XmlTypeAttribute, basta especificar o tipo do objeto sobreposto. Mas se estiver a sobrescrever um campo ou propriedade, também deve especificar o nome do membro sobrescrito.
Ao construir o XmlSerializer, passe o XmlAttributeOverrides para o XmlSerializer construtor.
Use o resultado XmlSerializer para serializar ou desserializar os objetos de classe derivados.
Construtores
| Name | Description |
|---|---|
| XmlAttributeOverrides() |
Inicializa uma nova instância da XmlAttributeOverrides classe. |
Propriedades
| Name | Description |
|---|---|
| Item[Type, String] |
Obtém o objeto associado ao tipo especificado (de classe base). O parâmetro membro especifica o membro da classe base que é sobreposto. |
| Item[Type] |
Obtém o objeto associado ao tipo de classe base especificado. |
Métodos
| Name | Description |
|---|---|
| Add(Type, String, XmlAttributes) |
Adiciona um XmlAttributes objeto à coleção de XmlAttributes objetos. O |
| Add(Type, XmlAttributes) |
Adiciona um XmlAttributes objeto à coleção de XmlAttributes objetos. O |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| ToString() |
Devolve uma cadeia que representa o objeto atual. (Herdado de Object) |
Aplica-se a
Ver também
- Deserialize(Stream)
- Serialize(TextWriter, Object)
- XmlSerializer
- XmlAttributes
- 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)