XmlArrayItemAttribute Classe

Definição

Representa um atributo que especifica os tipos derivados que o XmlSerializer pode colocar em uma matriz serializada.

public ref class XmlArrayItemAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.ReturnValue, AllowMultiple=true)]
public class XmlArrayItemAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.ReturnValue, AllowMultiple=true)>]
type XmlArrayItemAttribute = class
    inherit Attribute
Public Class XmlArrayItemAttribute
Inherits Attribute
Herança
XmlArrayItemAttribute
Atributos

Exemplos

O exemplo a seguir serializa uma classe nomeada Group que contém um campo chamado Employees que retorna uma matriz de Employee objetos. O exemplo aplica o XmlArrayItemAttribute campo, instruindo assim que XmlSerializer ele pode inserir objetos do tipo de classe base (Employee) e do tipo de classe derivada (Manager) na matriz serializada.

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

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

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

public ref class Manager: public Employee
{
public:
   int Level;
};

public ref class Group
{
public:

   /* The XmlArrayItemAttribute allows the XmlSerializer to insert
      both the base type (Employee) and derived type (Manager) 
      into serialized arrays. */

   [XmlArrayItem(Manager::typeid),
   XmlArrayItem(Employee::typeid)]
   array<Employee^>^Employees;

   /* Use the XmlArrayItemAttribute to specify types allowed
      in an array of Object items. */

   [XmlArray]
   [XmlArrayItem(Int32::typeid,
   ElementName="MyNumber"),
   XmlArrayItem(String::typeid,
   ElementName="MyString"),
   XmlArrayItem(Manager::typeid)]
   array<Object^>^ExtraInfo;
};

void SerializeObject( String^ filename )
{
   // Creates a new XmlSerializer.
   XmlSerializer^ s = gcnew XmlSerializer( Group::typeid );

   // Writing the XML file to disk requires a TextWriter.
   TextWriter^ writer = gcnew StreamWriter( filename );
   Group^ group = gcnew Group;
   Manager^ manager = gcnew Manager;
   Employee^ emp1 = gcnew Employee;
   Employee^ emp2 = gcnew Employee;
   manager->Name = "Consuela";
   manager->Level = 3;
   emp1->Name = "Seiko";
   emp2->Name = "Martina";
   array<Employee^>^emps = {manager,emp1,emp2};
   group->Employees = emps;

   // Creates an int and a string and assigns to ExtraInfo.
   array<Object^>^temp = {43,"Extra",manager};
   group->ExtraInfo = temp;

   // Serializes the object, and closes the StreamWriter.
   s->Serialize( writer, group );
   writer->Close();
}

void DeserializeObject( String^ filename )
{
   FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
   XmlSerializer^ x = gcnew XmlSerializer( Group::typeid );
   Group^ g = dynamic_cast<Group^>(x->Deserialize( fs ));
   Console::WriteLine( "Members:" );
   System::Collections::IEnumerator^ myEnum = g->Employees->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Employee^ e = safe_cast<Employee^>(myEnum->Current);
      Console::WriteLine( "\t{0}", e->Name );
   }
}

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

public class Group
{
   /* The XmlArrayItemAttribute allows the XmlSerializer to insert
      both the base type (Employee) and derived type (Manager)
      into serialized arrays. */

   [XmlArrayItem(typeof(Manager)),
   XmlArrayItem(typeof(Employee))]
   public Employee[] Employees;

   /* Use the XmlArrayItemAttribute to specify types allowed
      in an array of Object items. */
   [XmlArray]
   [XmlArrayItem (typeof(int),
   ElementName = "MyNumber"),
   XmlArrayItem (typeof(string),
   ElementName = "MyString"),
   XmlArrayItem(typeof(Manager))]
   public object [] ExtraInfo;
}

public class Employee
{
   public string Name;
}

public class Manager:Employee{
   public int Level;
}

public class Run
{
   public static void Main()
   {
      Run test = new Run();
      test.SerializeObject("TypeDoc.xml");
      test.DeserializeObject("TypeDoc.xml");
   }

   public void SerializeObject(string filename)
   {
      // Creates a new XmlSerializer.
      XmlSerializer s = new XmlSerializer(typeof(Group));

      // Writing the XML file to disk requires a TextWriter.
      TextWriter writer = new StreamWriter(filename);
      Group group = new Group();

      Manager manager = new Manager();
      Employee emp1 = new Employee();
      Employee emp2 = new Employee();
      manager.Name = "Consuela";
      manager.Level = 3;
      emp1.Name = "Seiko";
      emp2.Name = "Martina";
      Employee [] emps = new Employee[3]{manager, emp1, emp2};
      group.Employees = emps;

      // Creates an int and a string and assigns to ExtraInfo.
      group.ExtraInfo = new Object[3]{43, "Extra", manager};

      // Serializes the object, and closes the StreamWriter.
      s.Serialize(writer, group);
      writer.Close();
   }

   public void DeserializeObject(string filename)
   {
      FileStream fs = new FileStream(filename, FileMode.Open);
      XmlSerializer x = new XmlSerializer(typeof(Group));
      Group g = (Group) x.Deserialize(fs);
      Console.WriteLine("Members:");

      foreach(Employee e in g.Employees)
      {
         Console.WriteLine("\t" + e.Name);
      }
   }
}
Option Explicit
Option Strict

Imports System.IO
Imports System.Xml.Serialization

Public Class Group
    ' The XmlArrayItemAttribute allows the XmlSerializer to insert
    ' both the base type (Employee) and derived type (Manager)
    ' into serialized arrays. 
    
    <XmlArrayItem(GetType(Manager)), _
     XmlArrayItem(GetType(Employee))> _
    Public Employees() As Employee
    
    ' Use the XmlArrayItemAttribute to specify types allowed
    ' in an array of Object items. 
    <XmlArray(), _
     XmlArrayItem(GetType(Integer), ElementName := "MyNumber"), _
     XmlArrayItem(GetType(String), ElementName := "MyString"), _
     XmlArrayItem(GetType(Manager))> _
    Public ExtraInfo() As Object
End Class

Public Class Employee
    Public Name As String
End Class

Public Class Manager
    Inherits Employee
    Public Level As Integer
End Class


Public Class Run
    
    Public Shared Sub Main()
        Dim test As New Run()
        test.SerializeObject("TypeDoc.xml")
        test.DeserializeObject("TypeDoc.xml")
    End Sub
    
       
    Public Sub SerializeObject(ByVal filename As String)
        ' Creates a new XmlSerializer.
        Dim s As New XmlSerializer(GetType(Group))
        
        ' Writing the XML file to disk requires a TextWriter.
        Dim writer As New StreamWriter(filename)
        Dim group As New Group()
        
        Dim manager As New Manager()
        Dim emp1 As New Employee()
        Dim emp2 As New Employee()
        manager.Name = "Consuela"
        manager.Level = 3
        emp1.Name = "Seiko"
        emp2.Name = "Martina"
        Dim emps() As Employee = {manager, emp1, emp2}
        group.Employees = emps
        
        ' Creates an int and a string and assigns to ExtraInfo.
        group.ExtraInfo = New Object() {43, "Extra", manager}
        
        ' Serializes the object, and closes the StreamWriter.
        s.Serialize(writer, group)
        writer.Close()
    End Sub
    
    
    Public Sub DeserializeObject(ByVal filename As String)
        Dim fs As New FileStream(filename, FileMode.Open)
        Dim x As New XmlSerializer(GetType(Group))
        Dim g As Group = CType(x.Deserialize(fs), Group)
        Console.WriteLine("Members:")
        
        Dim e As Employee
        For Each e In  g.Employees
            Console.WriteLine(ControlChars.Tab & e.Name)
        Next e
    End Sub
End Class

Comentários

Pertence XmlArrayItemAttribute a uma família de atributos que controla como o XmlSerializer serializa ou desserializa um objeto. Para obter uma lista completa de atributos semelhantes, consulte Atributos que controlam a serialização XML.

Você pode aplicar o XmlArrayItemAttribute membro público de leitura/gravação que retorna uma matriz ou fornece acesso a uma. Por exemplo, um campo que retorna uma matriz de objetos, uma coleção, uma ArrayListou qualquer classe que implementa a IEnumerable interface.

O XmlArrayItemAttribute suporte ao polimorfismo, em outras XmlSerializer palavras, permite adicionar objetos derivados a uma matriz. Por exemplo, suponha que uma classe nomeada Mammal seja derivada de uma classe base chamada Animal. Suponha ainda que uma classe nomeada MyAnimals contenha um campo que retorna uma matriz de Animal objetos. Para permitir que a XmlSerializer serialização e o Animal Mammal tipo sejam serializados, aplique o XmlArrayItemAttribute campo duas vezes, cada vez especificando um dos dois tipos aceitáveis.

Observação

Você pode aplicar várias instâncias ou XmlArrayItemAttribute XmlElementAttribute especificar tipos de objetos que podem ser inseridos na matriz.

Observação

Não há suporte para a serialização de um campo ou propriedade que retorna uma interface ou uma matriz de interfaces.

Para obter mais informações sobre como usar atributos, consulte Atributos.

Observação

Você pode usar a palavra XmlArrayItem em seu código em vez de mais tempo XmlArrayItemAttribute.

Construtores

XmlArrayItemAttribute()

Inicializa uma nova instância da classe XmlArrayItemAttribute.

XmlArrayItemAttribute(String)

Inicializa uma nova instância da classe XmlArrayItemAttribute e especifica o nome do elemento XML gerado no documento XML.

XmlArrayItemAttribute(String, Type)

Inicializa uma nova instância da classe XmlArrayItemAttribute e especifica o nome do elemento XML gerado no documento XML e o Type que pode ser inserido no documento XML gerado.

XmlArrayItemAttribute(Type)

Inicializa uma nova instância da classe XmlArrayItemAttribute e especifica o Type que pode ser inserido na matriz serializada.

Propriedades

DataType

Obtém ou define o tipo de dados XML do elemento XML gerado.

ElementName

Obtém ou define o nome do elemento XML gerado.

Form

Obtém ou define um valor que indica se o nome do elemento XML gerado é qualificado.

IsNullable

Obtém ou define um valor que indica se o XmlSerializer deve serializar um membro como uma marca de XML vazia com o atributo xsi:nil definido como true.

Namespace

Obtém ou define o namespace do elemento XML gerado.

NestingLevel

Obtém ou define o nível em uma hierarquia de elementos XML que o XmlArrayItemAttribute afeta.

Type

Obtém ou define o tipo permitido em uma matriz.

TypeId

Quando implementado em uma classe derivada, obtém um identificador exclusivo para este Attribute.

(Herdado de Attribute)

Métodos

Equals(Object)

Retorna um valor que indica se essa instância é igual a um objeto especificado.

(Herdado de Attribute)
GetHashCode()

Retorna o código hash para a instância.

(Herdado de Attribute)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
IsDefaultAttribute()

Quando substituído em uma classe derivada, indica se o valor dessa instância é o valor padrão para a classe derivada.

(Herdado de Attribute)
Match(Object)

Quando substituído em uma classe derivada, retorna um valor que indica se essa instância é igual a um objeto especificado.

(Herdado de Attribute)
MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Implantações explícitas de interface

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição.

(Herdado de Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera as informações de tipo para um objeto, que pode ser usado para obter as informações de tipo para uma interface.

(Herdado de Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Retorna o número de interfaces de informações do tipo que um objeto fornece (0 ou 1).

(Herdado de Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fornece acesso a propriedades e métodos expostos por um objeto.

(Herdado de Attribute)

Aplica-se a

Confira também