XmlElementAttributes Classe

Definição

Representa uma coleção de objetos XmlElementAttribute usada pelo XmlSerializer para substituir a forma padrão que ele serializa uma classe.Represents a collection of XmlElementAttribute objects used by the XmlSerializer to override the default way it serializes a class.

public ref class XmlElementAttributes : System::Collections::CollectionBase
public class XmlElementAttributes : System.Collections.CollectionBase
type XmlElementAttributes = class
    inherit CollectionBase
Public Class XmlElementAttributes
Inherits CollectionBase
Herança
XmlElementAttributes

Exemplos

O exemplo a seguir serializa a classe Transportation, que contém um único campo chamado Vehicles que retorna uma ArrayList.The following example serializes the Transportation class, which contains a single field named Vehicles that returns an ArrayList. O exemplo primeiro aplica duas instâncias da classe XmlElementAttribute ao campo Vehicles que especifica os tipos de objetos que o XmlSerializer insere na matriz.The example first applies two instances of the XmlElementAttribute class to the Vehicles field that specifies the types of objects the XmlSerializer inserts into the array. Em seguida, o exemplo cria dois objetos XmlElementAttribute para substituir o comportamento dos atributos aplicados à propriedade Vehicles.The example then creates two XmlElementAttribute objects to override the behavior of the attributes applied to the Vehicles property. Os dois objetos de substituição são adicionados à coleção de XmlElementAttributes de um XmlAttributes.The two overriding objects are added to the XmlElementAttributes collection of an XmlAttributes. Por fim, o exemplo adiciona o XmlAttributes a um XmlAttributeOverrides, permitindo que o XmlSerializer Insira os novos tipos de objeto no ArrayList retornado pelo campo Vehicles.Lastly, the example adds the XmlAttributes to an XmlAttributeOverrides, allowing the XmlSerializer to insert the new object types into the ArrayList returned by the Vehicles field.

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

using namespace System;
using namespace System::IO;
using namespace System::Xml::Serialization;
using namespace System::Collections;
using namespace System::Xml;

public ref class Car
{
public:
   String^ Name;
};

public ref class Plane
{
public:
   String^ Name;
};

public ref class Truck
{
public:
   String^ Name;
};

public ref class Train
{
public:
   String^ Name;
};

public ref class Transportation
{
public:

   // Override these two XmlElementAttributes.

   [XmlElement(Car::typeid),
   XmlElement(Plane::typeid)]
   ArrayList^ Vehicles;
};

XmlSerializer^ CreateOverrider()
{
   // Create XmlAtrributes and XmlAttributeOverrides instances. 
   XmlAttributes^ attrs = gcnew XmlAttributes;
   XmlAttributeOverrides^ xOver = gcnew XmlAttributeOverrides;

   /* Create an XmlElementAttributes object to override 
      one of the attributes applied to the Vehicles property. */
   XmlElementAttribute^ xElement1 = gcnew XmlElementAttribute( Truck::typeid );

   // Add the XmlElementAttribute to the collection.
   attrs->XmlElements->Add( xElement1 );

   /* Create a second XmlElementAttribute and 
      add it to the collection. */
   XmlElementAttribute^ xElement2 = gcnew XmlElementAttribute( Train::typeid );
   attrs->XmlElements->Add( xElement2 );

   /* Add the XmlAttributes to the XmlAttributeOverrides,
      specifying the member to override. */
   xOver->Add( Transportation::typeid, "Vehicles", attrs );

   // Create the XmlSerializer, and return it.
   XmlSerializer^ xSer = gcnew XmlSerializer( Transportation::typeid,xOver );
   return xSer;
}

void SerializeObject( String^ filename )
{
   // Create an XmlSerializer instance.
   XmlSerializer^ xSer = CreateOverrider();

   // Create the object.
   Transportation^ myTransportation = gcnew Transportation;

   /* Create two new, overriding objects that can be
      inserted into the Vehicles array. */
   myTransportation->Vehicles = gcnew ArrayList;
   Truck^ myTruck = gcnew Truck;
   myTruck->Name = "MyTruck";
   Train^ myTrain = gcnew Train;
   myTrain->Name = "MyTrain";
   myTransportation->Vehicles->Add( myTruck );
   myTransportation->Vehicles->Add( myTrain );
   TextWriter^ writer = gcnew StreamWriter( filename );
   xSer->Serialize( writer, myTransportation );
}

int main()
{
   SerializeObject( "OverrideElement.xml" );
}
using System;
using System.IO;
using System.Xml.Serialization;
using System.Collections;
using System.Xml;

public class Transportation
{
   // Override these two XmlElementAttributes.
   [XmlElement(typeof(Car)),
   XmlElement(typeof(Plane))]
   public ArrayList Vehicles;
}

public class Car
{
   public string Name;
}

public class Plane
{
   public string Name;
}

public class Truck
{
   public string Name;
}

public class Train
{
   public string Name;
}

public class Test
{
   public static void Main()
   {
      Test t = new Test();
      t.SerializeObject("OverrideElement.xml");
   }

   public XmlSerializer CreateOverrider()
   {
      // Create XmlAtrributes and XmlAttributeOverrides instances. 
   
      XmlAttributes attrs = new XmlAttributes();

      XmlAttributeOverrides xOver = 
      new XmlAttributeOverrides();
      
      /* Create an XmlElementAttributes object to override 
      one of the attributes applied to the Vehicles property. */
      XmlElementAttribute xElement1 = 
      new XmlElementAttribute(typeof(Truck));
      // Add the XmlElementAttribute to the collection.
      attrs.XmlElements.Add(xElement1);

      /* Create a second XmlElementAttribute and 
      add it to the collection. */
      XmlElementAttribute xElement2 = 
      new XmlElementAttribute(typeof(Train));
      attrs.XmlElements.Add(xElement2);

      /* Add the XmlAttributes to the XmlAttributeOverrides,
      specifying the member to override. */
      xOver.Add(typeof(Transportation), "Vehicles", attrs);
      
      // Create the XmlSerializer, and return it.
      XmlSerializer xSer = new XmlSerializer
      (typeof(Transportation), xOver);
      return xSer;
   }

   public void SerializeObject(string filename)
   {
      // Create an XmlSerializer instance.
      XmlSerializer xSer = CreateOverrider();

      // Create the object.
      Transportation myTransportation = 
      new Transportation();

      /* Create two new, overriding objects that can be
      inserted into the Vehicles array. */
      myTransportation.Vehicles = new ArrayList();
      Truck myTruck = new Truck();
      myTruck.Name = "MyTruck";

      Train myTrain = new Train();
      myTrain.Name = "MyTrain";

      myTransportation.Vehicles.Add(myTruck);
      myTransportation.Vehicles.Add(myTrain);

      TextWriter writer = new StreamWriter(filename);
      xSer.Serialize(writer, myTransportation);
   }
}

Imports System.IO
Imports System.Xml.Serialization
Imports System.Collections
Imports System.Xml


Public Class Transportation
    ' Override these two XmlElementAttributes.
    <XmlElement(GetType(Car)), _
     XmlElement(GetType(Plane))> _
    Public Vehicles As ArrayList
End Class

Public Class Car
    Public Name As String
End Class

Public Class Plane
    Public Name As String
End Class

Public Class Truck
    Public Name As String
End Class

Public Class Train
    Public Name As String
End Class

Public Class Test
    
    Public Shared Sub Main()
        Dim t As New Test()
        t.SerializeObject("OverrideElement.xml")
    End Sub
    
    
    Public Function CreateOverrider() As XmlSerializer
        ' Create XmlAtrributes and XmlAttributeOverrides instances. 
        Dim attrs As New XmlAttributes()
        
        Dim xOver As New XmlAttributeOverrides()
        
        ' Create an XmlElementAttributes object to override
        ' one of the attributes applied to the Vehicles property. 
        Dim xElement1 As New XmlElementAttribute(GetType(Truck))
        ' Add the XmlElementAttribute to the collection.
        attrs.XmlElements.Add(xElement1)
        
        ' Create a second XmlElementAttribute and
        ' add it to the collection. 
        Dim xElement2 As New XmlElementAttribute(GetType(Train))
        attrs.XmlElements.Add(xElement2)
        
        ' Add the XmlAttributes to the XmlAttributeOverrides,
        ' specifying the member to override. 
        xOver.Add(GetType(Transportation), "Vehicles", attrs)
        
        ' Create the XmlSerializer, and return it.
        Dim xSer As New XmlSerializer(GetType(Transportation), xOver)
        Return xSer
    End Function
    
    
    Public Sub SerializeObject(ByVal filename As String)
        ' Create an XmlSerializer instance.
        Dim xSer As XmlSerializer = CreateOverrider()
        
        ' Create the object.
        Dim myTransportation As New Transportation()
        
        ' Create two new, overriding objects that can be
        ' inserted into the Vehicles array. 
        myTransportation.Vehicles = New ArrayList()
        Dim myTruck As New Truck()
        myTruck.Name = "MyTruck"
        
        Dim myTrain As New Train()
        myTrain.Name = "MyTrain"
        
        myTransportation.Vehicles.Add(myTruck)
        myTransportation.Vehicles.Add(myTrain)
        
        Dim writer As New StreamWriter(filename)
        xSer.Serialize(writer, myTransportation)
    End Sub
End Class

Comentários

O XmlElementAttributes é retornado pela propriedade XmlElements da classe XmlAttributes.The XmlElementAttributes is returned by the XmlElements property of the XmlAttributes class. Usando a classe XmlAttributeOverrides e a classe XmlAttributes, você pode substituir a forma padrão pela qual o XmlSerializer serializa uma classe.By using the XmlAttributeOverrides class and the XmlAttributes class, you can override the default way that the XmlSerializer serializes a class.

Construtores

XmlElementAttributes()

Inicia uma nova instância da classe XmlElementAttributes.Initializes a new instance of the XmlElementAttributes class.

Propriedades

Capacity

Obtém ou define o número de elementos que o CollectionBase pode conter.Gets or sets the number of elements that the CollectionBase can contain.

(Herdado de CollectionBase)
Count
InnerList

Obtém uma ArrayList que contém a lista de elementos na instância de CollectionBase.Gets an ArrayList containing the list of elements in the CollectionBase instance.

(Herdado de CollectionBase)
Item[Int32]

Obtém ou define o elemento no índice especificado.Gets or sets the element at the specified index.

List

Obtém uma IList que contém a lista de elementos na instância de CollectionBase.Gets an IList containing the list of elements in the CollectionBase instance.

(Herdado de CollectionBase)

Métodos

Add(XmlElementAttribute)

Adiciona um XmlElementAttribute à coleção.Adds an XmlElementAttribute to the collection.

Clear()
Contains(XmlElementAttribute)

Determina se a coleção contém o objeto especificado.Determines whether the collection contains the specified object.

CopyTo(XmlElementAttribute[], Int32)

Copia o XmlElementAttributes, ou parte dele, para uma matriz unidimensional.Copies the XmlElementAttributes, or a portion of it to a one-dimensional array.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Herdado de Object)
GetEnumerator()
GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
IndexOf(XmlElementAttribute)

Obtém o índice do XmlElementAttribute especificado.Gets the index of the specified XmlElementAttribute.

Insert(Int32, XmlElementAttribute)

Insere um XmlElementAttribute na coleção.Inserts an XmlElementAttribute into the collection.

MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
OnClear()

Executa processos personalizados adicionais ao limpar o conteúdo da instância CollectionBase.Performs additional custom processes when clearing the contents of the CollectionBase instance.

(Herdado de CollectionBase)
OnClearComplete()

Executa processos adicionais personalizados após limpar o conteúdo da instância CollectionBase.Performs additional custom processes after clearing the contents of the CollectionBase instance.

(Herdado de CollectionBase)
OnInsert(Int32, Object)

Executa os processos personalizados adicionais antes de inserir um novo elemento na instância CollectionBase.Performs additional custom processes before inserting a new element into the CollectionBase instance.

(Herdado de CollectionBase)
OnInsertComplete(Int32, Object)

Executa processos personalizados adicionais após inserir um novo elemento na instância CollectionBase.Performs additional custom processes after inserting a new element into the CollectionBase instance.

(Herdado de CollectionBase)
OnRemove(Int32, Object)

Executa processos personalizados adicionais ao remover um elemento da instância CollectionBase.Performs additional custom processes when removing an element from the CollectionBase instance.

(Herdado de CollectionBase)
OnRemoveComplete(Int32, Object)

Executa processos personalizados adicionais após remover um elemento da instância CollectionBase.Performs additional custom processes after removing an element from the CollectionBase instance.

(Herdado de CollectionBase)
OnSet(Int32, Object, Object)

Executa processos personalizados adicionais antes de definir um valor na instância CollectionBase.Performs additional custom processes before setting a value in the CollectionBase instance.

(Herdado de CollectionBase)
OnSetComplete(Int32, Object, Object)

Executa processos personalizados adicionais após definir um valor na instância CollectionBase.Performs additional custom processes after setting a value in the CollectionBase instance.

(Herdado de CollectionBase)
OnValidate(Object)

Executa processos personalizados adicionais ao validar um valor.Performs additional custom processes when validating a value.

(Herdado de CollectionBase)
Remove(XmlElementAttribute)

Remove o objeto especificado da coleção.Removes the specified object from the collection.

RemoveAt(Int32)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Herdado de Object)

Implantações explícitas de interface

ICollection.CopyTo(Array, Int32)
ICollection.IsSynchronized
ICollection.SyncRoot
IList.Add(Object)
IList.Contains(Object)
IList.IndexOf(Object)
IList.Insert(Int32, Object)
IList.IsFixedSize
IList.IsReadOnly
IList.Item[Int32]
IList.Remove(Object)

Métodos de Extensão

Cast<TResult>(IEnumerable)

Converte os elementos de um IEnumerable para o tipo especificado.Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

Filtra os elementos de um IEnumerable com base em um tipo especificado.Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

Habilita a paralelização de uma consulta.Enables parallelization of a query.

AsQueryable(IEnumerable)

Converte um IEnumerable em um IQueryable.Converts an IEnumerable to an IQueryable.

Aplica-se a

Veja também