Este artigo foi traduzido por máquina. Para visualizar o arquivo em inglês, marque a caixa de seleção Inglês. Você também pode exibir o texto Em inglês em uma janela pop-up, movendo o ponteiro do mouse sobre o texto.
Tradução
Inglês

Classe XmlAttributeOverrides

 

Permite a substituição de propriedade, campo e atributos de classe quando você usa o XmlSerializer para serializar ou desserializar um objeto.

Namespace:   System.Xml.Serialization
Assembly:  System.Xml (em System.Xml.dll)

System.Object
  System.Xml.Serialization.XmlAttributeOverrides

public class XmlAttributeOverrides

NomeDescrição
System_CAPS_pubmethodXmlAttributeOverrides()

Inicializa uma nova instância da classe XmlAttributeOverrides.

NomeDescrição
System_CAPS_pubpropertyItem[Type]

Obtém o objeto associado ao tipo de classe base especificado.

System_CAPS_pubpropertyItem[Type, String]

Obtém o objeto associado com o tipo (classe base) especificado. O parâmetro de membro Especifica o membro da classe base que é substituído.

NomeDescrição
System_CAPS_pubmethodAdd(Type, String, XmlAttributes)

Adiciona um XmlAttributes objeto à coleção de XmlAttributes objetos. O type parâmetro especifica um objeto a ser substituído. O member parâmetro especifica o nome de um membro é substituído.

System_CAPS_pubmethodAdd(Type, XmlAttributes)

Adiciona um XmlAttributes objeto à coleção de XmlAttributes objetos. O type parâmetro especifica um objeto a ser substituído pela XmlAttributes objeto.

System_CAPS_pubmethodEquals(Object)

Verifica se o objeto especificado é igual ao objeto atual. (Herdado de Object.)

System_CAPS_protmethodFinalize()

Permite que um objeto tente liberar recursos e executar outras operações de limpeza antes que ele seja recuperado pela coleta de lixo. (Herdado de Object.)

System_CAPS_pubmethodGetHashCode()

Serve como a função de hash padrão.(Herdado de Object.)

System_CAPS_pubmethodGetType()

Obtém o Type da instância atual.(Herdado de Object.)

System_CAPS_protmethodMemberwiseClone()

Cria uma cópia superficial do Object atual.(Herdado de Object.)

System_CAPS_pubmethodToString()

Retorna uma string que representa o objeto atual.(Herdado de Object.)

The T:System.Xml.Serialization.XmlAttributeOverrides enables the T:System.Xml.Serialization.XmlSerializer to override the default way of serializing a set of objects. 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. For example, instead of serializing members of a class instance as XML elements, you can serialize them as XML attributes, resulting in a more efficient document to transport.

After you create an T:System.Xml.Serialization.XmlAttributeOverrides object, you pass it as an argument to the M:System.Xml.Serialization.XmlSerializer.#ctor constructor. The resulting T:System.Xml.Serialization.XmlSerializer uses the data contained by the T:System.Xml.Serialization.XmlAttributeOverrides to override attributes that control how objects are serialized. To accomplish this, the T:System.Xml.Serialization.XmlAttributeOverrides contains a collection of the object types that are overridden, as well as an T:System.Xml.Serialization.XmlAttributes object associated with each overridden object type. The T:System.Xml.Serialization.XmlAttributes object itself contains an appropriate set of attribute objects that control how each field, property, or class is serialized.

The process for creating and using an T:System.Xml.Serialization.XmlAttributeOverrides object is as follows:

  1. Create an T:System.Xml.Serialization.XmlAttributes object.

  2. Create an attribute object that is appropriate to the object being overridden. For example, to override a field or property, create an T:System.Xml.Serialization.XmlElementAttribute, using the new, derived type. You can optionally assign a new P:System.Xml.Serialization.XmlElementAttribute.ElementName, or P:System.Xml.Serialization.XmlElementAttribute.Namespace that overrides the base class's attribute name or namespace.

  3. Add the attribute object to the appropriate T:System.Xml.Serialization.XmlAttributes property or collection. For example, you would add the T:System.Xml.Serialization.XmlElementAttribute to the P:System.Xml.Serialization.XmlAttributes.XmlElements collection of the T:System.Xml.Serialization.XmlAttributes object, specifying the member name that is being overridden.

  4. Create an T:System.Xml.Serialization.XmlAttributeOverrides object.

  5. Using the M:System.Xml.Serialization.XmlAttributeOverrides.Add(System.Type,System.Xml.Serialization.XmlAttributes) method, add the T:System.Xml.Serialization.XmlAttributes object to the T:System.Xml.Serialization.XmlAttributeOverrides object. If the object being overridden is an T:System.Xml.Serialization.XmlRootAttribute or T:System.Xml.Serialization.XmlTypeAttribute, you need only to specify the type of the overridden object. But if you are overriding a field or property, you must also specify the name of the overridden member.

  6. When constructing the T:System.Xml.Serialization.XmlSerializer, pass the T:System.Xml.Serialization.XmlAttributeOverrides to the M:System.Xml.Serialization.XmlSerializer.#ctor constructor.

  7. Use the resulting T:System.Xml.Serialization.XmlSerializer to serialize or deserialize the derived class objects.

The following example serializes a class named Orchestra, which contains a single field named Instruments that returns an array of Instrument objects. A second class named Brass inherits from the Instrument class. The example uses an instance of the T:System.Xml.Serialization.XmlAttributeOverrides class to override the Instrument field, allowing the field to accept Brass objects.

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);
      }
   }
}

Plataforma Universal do Windows
Disponível desde 8
.NET Framework
Disponível desde 1.1
Biblioteca de Classes Portátil
Com suporte no: plataformas portáteis do .NET
Silverlight
Disponível desde 2.0
Windows Phone Silverlight
Disponível desde 7.0
Windows Phone
Disponível desde 8.1

Quaisquer membros estáticos públicos ( Compartilhado no Visual Basic) desse tipo são thread-safe. Não há garantia de que qualquer membro de instância seja thread-safe.

Retornar ao início
Mostrar: