XmlArrayItemAttribute Klasa

Definicja

Reprezentuje atrybut określający typy pochodne, które XmlSerializer mogą umieścić w serializacji tablicy.

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
Dziedziczenie
XmlArrayItemAttribute
Atrybuty

Przykłady

Poniższy przykład serializuje klasę o nazwie , która zawiera pole o Group nazwie Employees , które zwraca tablicę Employee obiektów. Przykład dotyczy XmlArrayItemAttribute pola, dlatego instruujeXmlSerializer, że może wstawić obiekty zarówno typu klasy bazowej () jak i typu klasy pochodnej (EmployeeManager) do tablicy serializowanej.

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

Uwagi

Element XmlArrayItemAttribute należy do rodziny atrybutów, które steruje serializami XmlSerializer lub deserializuje obiekt. Aby uzyskać pełną listę podobnych atrybutów, zobacz Atrybuty kontrolujące serializacji XML.

Można zastosować XmlArrayItemAttribute element do dowolnego publicznego elementu członkowskiego odczytu/zapisu, który zwraca tablicę lub zapewnia dostęp do niej. Na przykład pole zwracające tablicę obiektów, kolekcję, klasę lub dowolną ArrayListklasę, która implementuje IEnumerable interfejs.

Obiekt XmlArrayItemAttribute obsługuje polimorfizm — innymi słowy, umożliwia XmlSerializer dodawanie obiektów pochodnych do tablicy. Załóżmy na przykład, że klasa o nazwie Mammal pochodzi z klasy bazowej o nazwie Animal. Ponadto załóżmy, że klasa o nazwie MyAnimals zawiera pole zwracające tablicę Animal obiektów. Aby umożliwić XmlSerializer serializowanie zarówno typu Animal , jak i Mammal , zastosuj XmlArrayItemAttribute wartość do pola dwa razy, za każdym razem określając jeden z dwóch dopuszczalnych typów.

Note

Można zastosować wiele wystąpień XmlArrayItemAttribute obiektu lub XmlElementAttribute , aby określić typy obiektów, które można wstawić do tablicy.

Note

Serializacja pola lub właściwości zwracającej interfejs lub tablicę interfejsów nie jest obsługiwana.

Aby uzyskać więcej informacji na temat używania atrybutów, zobacz Atrybuty.

Note

Możesz użyć słowa XmlArrayItem w kodzie zamiast dłuższego XmlArrayItemAttribute.

Konstruktory

Nazwa Opis
XmlArrayItemAttribute()

Inicjuje nowe wystąpienie klasy XmlArrayItemAttribute.

XmlArrayItemAttribute(String, Type)

Inicjuje nowe wystąpienie XmlArrayItemAttribute klasy i określa nazwę elementu XML wygenerowanego w dokumencie XML oraz element Type , który można wstawić do wygenerowanego dokumentu XML.

XmlArrayItemAttribute(String)

Inicjuje nowe wystąpienie XmlArrayItemAttribute klasy i określa nazwę elementu XML wygenerowanego w dokumencie XML.

XmlArrayItemAttribute(Type)

Inicjuje nowe wystąpienie XmlArrayItemAttribute klasy i określa Type , które można wstawić do tablicy serializowanej.

Właściwości

Nazwa Opis
DataType

Pobiera lub ustawia typ danych XML wygenerowanego elementu XML.

ElementName

Pobiera lub ustawia nazwę wygenerowanego elementu XML.

Form

Pobiera lub ustawia wartość wskazującą, czy nazwa wygenerowanego elementu XML jest kwalifikowana.

IsNullable

Pobiera lub ustawia wartość wskazującą, czy XmlSerializer element członkowski musi serializować jako pusty tag XML z atrybutem ustawionym xsi:nil na truewartość .

Namespace

Pobiera lub ustawia przestrzeń nazw wygenerowanego elementu XML.

NestingLevel

Pobiera lub ustawia poziom w hierarchii elementów XML, które XmlArrayItemAttribute mają wpływ.

Type

Pobiera lub ustawia typ dozwolony w tablicy.

TypeId

Po zaimplementowaniu w klasie pochodnej pobiera unikatowy identyfikator dla tego Attribute.

(Odziedziczone po Attribute)

Metody

Nazwa Opis
Equals(Object)

Zwraca wartość wskazującą, czy to wystąpienie jest równe określonemu obiektowi.

(Odziedziczone po Attribute)
GetHashCode()

Zwraca kod skrótu dla tego wystąpienia.

(Odziedziczone po Attribute)
GetType()

Pobiera Type bieżącego wystąpienia.

(Odziedziczone po Object)
IsDefaultAttribute()

Po zastąpieniu w klasie pochodnej wskazuje, czy wartość tego wystąpienia jest wartością domyślną dla klasy pochodnej.

(Odziedziczone po Attribute)
Match(Object)

Po zastąpieniu w klasie pochodnej zwraca wartość wskazującą, czy to wystąpienie jest równe określonemu obiektowi.

(Odziedziczone po Attribute)
MemberwiseClone()

Tworzy płytkią kopię bieżącego Object.

(Odziedziczone po Object)
ToString()

Zwraca ciąg reprezentujący bieżący obiekt.

(Odziedziczone po Object)

Jawne implementacje interfejsu

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

Zestaw nazw jest mapowany na odpowiedni zestaw identyfikatorów wysyłania.

(Odziedziczone po Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Pobiera informacje o typie obiektu, którego można użyć do uzyskania informacji o typie dla interfejsu.

(Odziedziczone po Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Pobiera informację o liczbie typów interfejsów, jakie zawiera obiekt (0 lub 1).

(Odziedziczone po Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Zapewnia dostęp do właściwości i metod uwidocznionych przez obiekt.

(Odziedziczone po Attribute)

Dotyczy

Zobacz też