XmlArrayItemAttribute Classe

Definição

Representa um atributo que especifica os tipos derivados que podem XmlSerializer colocar num array serializado.

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 seguinte serializa uma classe nomeada Group que contém um campo nomeado Employees que devolve um array de Employee objetos. O exemplo aplica-se ao XmlArrayItemAttribute campo, instruindo assim que pode XmlSerializer inserir objetos tanto do tipo base (Employee) como do tipo de classe derivada (Manager) no array serializado.

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

Observações

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

Podes aplicar o XmlArrayItemAttribute a qualquer membro público de leitura/escrita que devolva um array ou que forneça acesso a um. Por exemplo, um campo que devolve um array de objetos, uma coleção, um ArrayList, ou qualquer classe que implemente a IEnumerable interface.

Suporta XmlArrayItemAttribute polimorfismo — ou seja, permite adicionar XmlSerializer objetos derivados a um array. Por exemplo, suponha que uma classe nomeada Mammal é derivada de uma classe base chamada Animal. Suponha ainda que uma classe nomeada MyAnimals contém um campo que devolve um array de Animal objetos. Para permitir que o XmlSerializer serialize ambos os tipos e AnimalMammal , aplica o XmlArrayItemAttribute ao campo duas vezes, especificando cada vez um dos dois tipos aceitáveis.

Note

Pode aplicar múltiplas instâncias do XmlArrayItemAttribute ou XmlElementAttribute para especificar tipos de objetos que podem ser inseridos no array.

Note

A serialização de um campo ou propriedade que devolve uma interface ou array de interfaces não é suportada.

Para mais informações sobre o uso de atributos, consulte Atributos.

Note

Podes usar a palavra XmlArrayItem no teu código em vez do mais longo XmlArrayItemAttribute.

Construtores

Name Description
XmlArrayItemAttribute()

Inicializa uma nova instância da XmlArrayItemAttribute classe.

XmlArrayItemAttribute(String, Type)

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

XmlArrayItemAttribute(String)

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

XmlArrayItemAttribute(Type)

Inicializa uma nova instância da XmlArrayItemAttribute classe e especifica que Type pode ser inserida no array serializado.

Propriedades

Name Description
DataType

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

ElementName

Recebe 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

Recebe ou define um valor que indica se deve XmlSerializer serializar um membro como uma etiqueta XML vazia com o xsi:nil atributo definido como true.

Namespace

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

NestingLevel

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

Type

Obtém ou define o tipo permitido num array.

TypeId

Quando implementado numa classe derivada, obtém um identificador único para esta Attribute.

(Herdado de Attribute)

Métodos

Name Description
Equals(Object)

Devolve um valor que indica se esta instância é igual a um objeto especificado.

(Herdado de Attribute)
GetHashCode()

Devolve o código de hash para esta instância.

(Herdado de Attribute)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
IsDefaultAttribute()

Quando sobrescrito numa classe derivada, indica se o valor desta instância é o valor padrão para a classe derivada.

(Herdado de Attribute)
Match(Object)

Quando sobrescrito numa classe derivada, devolve um valor que indica se esta instância é igual a um objeto especificado.

(Herdado de Attribute)
MemberwiseClone()

Cria uma cópia superficial do atual Object.

(Herdado de Object)
ToString()

Devolve uma cadeia que representa o objeto atual.

(Herdado de Object)

Implementações de Interface Explícita

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

Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de despacho.

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

Recupera a informação de tipo de um objeto, que pode ser usada para obter a informação de tipo para uma interface.

(Herdado de Attribute)
_Attribute.GetTypeInfoCount(UInt32)

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

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

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

(Herdado de Attribute)

Aplica-se a

Ver também