Partager via


XmlArrayAttribute Classe

Définition

Spécifie que le XmlSerializer doit sérialiser un membre de classe particulier en tant que tableau d’éléments XML.

public ref class XmlArrayAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.ReturnValue, AllowMultiple=false)]
public class XmlArrayAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.ReturnValue, AllowMultiple=false)>]
type XmlArrayAttribute = class
    inherit Attribute
Public Class XmlArrayAttribute
Inherits Attribute
Héritage
XmlArrayAttribute
Attributs

Exemples

L’exemple suivant sérialise une instance de classe dans un document XML qui contient plusieurs tableaux d’objets. Il XmlArrayAttribute est appliqué aux membres qui deviennent des tableaux d’éléments XML.

using System;
using System.IO;
using System.Xml.Serialization;
using System.Xml;

public class Run
{
   public static void Main()
   {
      Run test = new Run();
      test.SerializeDocument("books.xml");
   }

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

      // Writing the file requires a StreamWriter.
      TextWriter myWriter= new StreamWriter(filename);

      // Creates an instance of the class to serialize.
      MyRootClass myRootClass = new MyRootClass();

      /* Uses a basic method of creating an XML array: Create and
      populate a string array, and assign it to the
      MyStringArray property. */

      string [] myString = {"Hello", "world", "!"};
      myRootClass.MyStringArray = myString;

      /* Uses a more advanced method of creating an array:
         create instances of the Item and BookItem, where BookItem
         is derived from Item. */
      Item item1 = new Item();
      BookItem item2 = new BookItem();

      // Sets the objects' properties.
      item1.ItemName = "Widget1";
      item1.ItemCode = "w1";
      item1.ItemPrice = 231;
      item1.ItemQuantity = 3;

      item2.ItemCode = "w2";
      item2.ItemPrice = 123;
      item2.ItemQuantity = 7;
      item2.ISBN = "34982333";
      item2.Title = "Book of Widgets";
      item2.Author = "John Smith";

      // Fills the array with the items.
      Item [] myItems = {item1,item2};

      // Sets the class's Items property to the array.
      myRootClass.Items = myItems;

      /* Serializes the class, writes it to disk, and closes
         the TextWriter. */
      s.Serialize(myWriter, myRootClass);
      myWriter.Close();
   }
}

// This is the class that will be serialized.
public class MyRootClass
{
   private Item [] items;

   /* Here is a simple way to serialize the array as XML. Using the
      XmlArrayAttribute, assign an element name and namespace. The
      IsNullable property determines whether the element will be
      generated if the field is set to a null value. If set to true,
      the default, setting it to a null value will cause the XML
      xsi:null attribute to be generated. */
   [XmlArray(ElementName = "MyStrings",
   Namespace = "http://www.cpandl.com", IsNullable = true)]
   public string[] MyStringArray;

   /* Here is a more complex example of applying an
      XmlArrayAttribute. The Items property can contain both Item
      and BookItem objects. Use the XmlArrayItemAttribute to specify
      that both types can be inserted into the array. */
   [XmlArrayItem(ElementName= "Item",
   IsNullable=true,
   Type = typeof(Item),
   Namespace = "http://www.cpandl.com"),
   XmlArrayItem(ElementName = "BookItem",
   IsNullable = true,
   Type = typeof(BookItem),
   Namespace = "http://www.cohowinery.com")]
   [XmlArray]
   public Item []Items
   {
      get{return items;}
      set{items = value;}
   }
}

public class Item{
   [XmlElement(ElementName = "OrderItem")]
   public string ItemName;
   public string ItemCode;
   public decimal ItemPrice;
   public int ItemQuantity;
}

public class BookItem:Item
{
   public string Title;
   public string Author;
   public string ISBN;
}
Option Explicit
Option Strict

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


Public Class Run
    
    Public Shared Sub Main()
        Dim test As New Run()
        test.SerializeDocument("books.xml")
    End Sub
    
    
    Public Sub SerializeDocument(ByVal filename As String)
        ' Creates a new XmlSerializer.
        Dim s As New XmlSerializer(GetType(MyRootClass))
        
        ' Writing the file requires a StreamWriter.
        Dim myWriter As New StreamWriter(filename)
        
        ' Creates an instance of the class to serialize. 
        Dim myRootClass As New MyRootClass()
        
        ' Uses a basic method of creating an XML array: Create and
        ' populate a string array, and assign it to the
        ' MyStringArray property. 
        
        Dim myString() As String =  {"Hello", "world", "!"}
        myRootClass.MyStringArray = myString
        
        ' Uses a more advanced method of creating an array:
        ' create instances of the Item and BookItem, where BookItem
        ' is derived from Item. 
        Dim item1 As New Item()
        Dim item2 As New BookItem()
        
        ' Sets the objects' properties.
        With item1
            .ItemName = "Widget1"
            .ItemCode = "w1"
            .ItemPrice = 231
            .ItemQuantity = 3
        End With

        With item2
            .ItemCode = "w2"
            .ItemPrice = 123
            .ItemQuantity = 7
            .ISBN = "34982333"
            .Title = "Book of Widgets"
            .Author = "John Smith"
        End With
        
        ' Fills the array with the items.
        Dim myItems() As Item =  {item1, item2}
        
        ' Set class's Items property to the array.
        myRootClass.Items = myItems
        
        ' Serializes the class, writes it to disk, and closes
        ' the TextWriter. 
        s.Serialize(myWriter, myRootClass)
        myWriter.Close()
    End Sub
End Class


' This is the class that will be serialized.
Public Class MyRootClass
    Private myItems() As Item
    
    ' Here is a simple way to serialize the array as XML. Using the
    ' XmlArrayAttribute, assign an element name and namespace. The
    ' IsNullable property determines whether the element will be
    ' generated if the field is set to a null value. If set to true,
    ' the default, setting it to a null value will cause the XML
    ' xsi:null attribute to be generated.
    <XmlArray(ElementName := "MyStrings", _
         Namespace := "http://www.cpandl.com", _
         IsNullable := True)> _
    Public MyStringArray() As String
    
    ' Here is a more complex example of applying an
    ' XmlArrayAttribute. The Items property can contain both Item
    ' and BookItem objects. Use the XmlArrayItemAttribute to specify
    ' that both types can be inserted into the array.
    <XmlArrayItem(ElementName := "Item", _
        IsNullable := True, _
        Type := GetType(Item), _
        Namespace := "http://www.cpandl.com"), _
     XmlArrayItem(ElementName := "BookItem", _
        IsNullable := True, _
        Type := GetType(BookItem), _
        Namespace := "http://www.cohowinery.com"), _
     XmlArray()> _
    Public Property Items As Item()
        Get
            Return myItems
        End Get
        Set
            myItems = value
        End Set
    End Property
End Class
 
Public Class Item
    <XmlElement(ElementName := "OrderItem")> _
    Public ItemName As String
    Public ItemCode As String
    Public ItemPrice As Decimal
    Public ItemQuantity As Integer
End Class

Public Class BookItem
    Inherits Item
    Public Title As String
    Public Author As String
    Public ISBN As String
End Class

Remarques

Appartient XmlArrayAttribute à une famille d’attributs qui contrôle la façon dont le XmlSerializer sérialise ou désérialise un objet. Pour obtenir la liste complète des attributs similaires, consultez Attributs qui contrôlent la sérialisation XML.

Vous pouvez appliquer le XmlArrayAttribute champ public à une propriété en lecture/écriture qui retourne un tableau d’objets. Vous pouvez également l’appliquer à des collections et des champs qui retournent un ArrayList ou n’importe quel champ qui retourne un objet qui implémente l’interface IEnumerable .

Lorsque vous appliquez un XmlArrayAttribute membre de classe, la Serialize méthode de la XmlSerializer classe génère une séquence imbriquée d’éléments XML à partir de ce membre. Un document de schéma XML (fichier .xsd), indique un tableau tel qu’un complexType. Par exemple, si la classe à sérialiser représente un bon de commande, vous pouvez générer un tableau d’éléments achetés en appliquant le XmlArrayAttribute champ public qui retourne un tableau d’objets qui représentent des éléments de commande.

Si aucun attribut n’est appliqué à un champ public ou à une propriété qui retourne un tableau d’objets de type complexe ou primitif, il XmlSerializer génère une séquence imbriquée d’éléments XML par défaut. Pour contrôler plus précisément les éléments XML générés, appliquez un XmlArrayItemAttribute et un XmlArrayAttribute au champ ou à la propriété. Par exemple, par défaut, le nom de l’élément XML généré est dérivé de l’identificateur membre. Vous pouvez modifier le nom de l’élément XML généré en définissant la ElementName propriété.

Si vous sérialisez un tableau qui contient des éléments d’un type spécifique et toutes les classes dérivées de ce type, vous devez utiliser la XmlArrayItemAttribute méthode pour déclarer chacun des types.

Note

Vous pouvez utiliser XmlArray dans votre code au lieu du plus long XmlArrayAttribute.

Pour plus d’informations sur l’utilisation d’attributs, consultez Attributs.

Constructeurs

Nom Description
XmlArrayAttribute()

Initialise une nouvelle instance de la classe XmlArrayAttribute.

XmlArrayAttribute(String)

Initialise une nouvelle instance de la XmlArrayAttribute classe et spécifie le nom de l’élément XML généré dans l’instance de document XML.

Propriétés

Nom Description
ElementName

Obtient ou définit le nom d’élément XML donné au tableau sérialisé.

Form

Obtient ou définit une valeur qui indique si le nom de l’élément XML généré par l’élément XmlSerializer est qualifié ou non qualifié.

IsNullable

Obtient ou définit une valeur qui indique si le XmlSerializer membre doit sérialiser un membre en tant que balise XML vide avec l’attribut xsi:nil défini sur true.

Namespace

Obtient ou définit l’espace de noms de l’élément XML.

Order

Obtient ou définit l’ordre explicite dans lequel les éléments sont sérialisés ou désérialisés.

TypeId

En cas d’implémentation dans une classe dérivée, obtient un identificateur unique pour cette Attribute.

(Hérité de Attribute)

Méthodes

Nom Description
Equals(Object)

Retourne une valeur qui indique si cette instance est égale à un objet spécifié.

(Hérité de Attribute)
GetHashCode()

Retourne le code de hachage pour cette instance.

(Hérité de Attribute)
GetType()

Obtient la Type de l’instance actuelle.

(Hérité de Object)
IsDefaultAttribute()

En cas de substitution dans une classe dérivée, indique si la valeur de cette instance est la valeur par défaut de la classe dérivée.

(Hérité de Attribute)
Match(Object)

En cas de substitution dans une classe dérivée, retourne une valeur qui indique si cette instance est égale à un objet spécifié.

(Hérité de Attribute)
MemberwiseClone()

Crée une copie superficielle du Objectactuel.

(Hérité de Object)
ToString()

Retourne une chaîne qui représente l’objet actuel.

(Hérité de Object)

Implémentations d’interfaces explicites

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

Mappe un jeu de noms avec un jeu correspondant d'identificateurs de dispatch.

(Hérité de Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Récupère les informations de type d’un objet, qui peuvent être utilisées pour obtenir les informations de type d’une interface.

(Hérité de Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Récupère le nombre d'interfaces d'informations de type fourni par un objet (0 ou 1).

(Hérité de Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fournit l’accès aux propriétés et méthodes exposées par un objet.

(Hérité de Attribute)

S’applique à

Voir aussi