XmlArrayAttribute Klasa

Definicja

Określa, że XmlSerializer musi serializacji określonej składowej klasy jako tablicy elementów 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)]
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
[<System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.ReturnValue)>]
type XmlArrayAttribute = class
    inherit Attribute
Public Class XmlArrayAttribute
Inherits Attribute
Dziedziczenie
XmlArrayAttribute
Atrybuty

Przykłady

Poniższy przykład serializuje wystąpienie klasy w dokumencie XML zawierającym kilka tablic obiektów. Element XmlArrayAttribute jest stosowany do elementów członkowskich, które stają się tablicami elementów XML.

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

using namespace System;
using namespace System::IO;
using namespace System::Xml::Serialization;
using namespace System::Xml;
public ref class Item
{
public:

   [XmlElement(ElementName="OrderItem")]
   String^ ItemName;
   String^ ItemCode;
   Decimal ItemPrice;
   int ItemQuantity;
};

public ref class BookItem: public Item
{
public:
   String^ Title;
   String^ Author;
   String^ ISBN;
};

// This is the class that will be serialized.
public ref class MyRootClass
{
private:
   array<Item^>^items;

public:

   /* 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)]
   array<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=Item::typeid,
   Namespace="http://www.cpandl.com"),
   XmlArrayItem(ElementName="BookItem",
   IsNullable=true,
   Type=BookItem::typeid,
   Namespace="http://www.cohowinery.com")]
   [XmlArray]
   property array<Item^>^ Items 
   {
      array<Item^>^ get()
      {
         return items;
      }

      void set( array<Item^>^value )
      {
         items = value;
      }
   }
};

public ref class Run
{
public:
   void SerializeDocument( String^ filename )
   {
      // Creates a new XmlSerializer.
      XmlSerializer^ s = gcnew XmlSerializer( MyRootClass::typeid );

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

      // Creates an instance of the class to serialize. 
      MyRootClass^ myRootClass = gcnew MyRootClass;

      /* Uses a basic method of creating an XML array: Create and 
            populate a string array, and assign it to the 
            MyStringArray property. */
      array<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 = gcnew Item;
      BookItem^ item2 = gcnew 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.
      array<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();
   }
};

int main()
{
   Run^ test = gcnew Run;
   test->SerializeDocument( "books.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

Uwagi

Element XmlArrayAttribute należy do rodziny atrybutów, które kontrolują sposób XmlSerializer serializacji lub deserializacji obiektu. Aby uzyskać pełną listę podobnych atrybutów, zobacz Atrybuty, które kontrolują serializacji XML.

Można zastosować element XmlArrayAttribute do pola publicznego lub właściwości odczytu/zapisu, która zwraca tablicę obiektów. Można go również zastosować do kolekcji i pól, które zwracają dowolne pole zwracające ArrayList obiekt implementujący IEnumerable interfejs.

Po zastosowaniu XmlArrayAttribute elementu do składowej Serialize klasy metoda XmlSerializer klasy generuje zagnieżdżona sekwencję elementów XML z tego elementu członkowskiego. Dokument schematu XML (plik xsd) wskazuje taką tablicę complexTypejak . Jeśli na przykład klasa do serializacji reprezentuje zamówienie zakupu, można wygenerować tablicę zakupionych elementów, stosując element do XmlArrayAttribute pola publicznego, które zwraca tablicę obiektów reprezentujących elementy zamówienia.

Jeśli żadne atrybuty nie są stosowane do pola publicznego lub właściwości zwracającej tablicę obiektów typu złożonego lub pierwotnego, XmlSerializer domyślnie generuje zagnieżdżona sekwencja elementów XML. Aby dokładniej kontrolować, jakie elementy XML są generowane, zastosuj XmlArrayItemAttribute element i XmlArrayAttribute do pola lub właściwości. Na przykład domyślnie nazwa wygenerowanego elementu XML pochodzi od identyfikatora elementu członkowskiego Można zmienić nazwę wygenerowanego elementu XML, ustawiając ElementName właściwość .

W przypadku serializacji tablicy zawierającej elementy określonego typu i wszystkich klas pochodnych od tego typu, należy użyć klasy XmlArrayItemAttribute , aby zadeklarować każdy z typów.

Uwaga

Możesz użyć XmlArray w kodzie zamiast dłuższego XmlArrayAttribute.

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

Konstruktory

XmlArrayAttribute()

Inicjuje nowe wystąpienie klasy XmlArrayAttribute.

XmlArrayAttribute(String)

Inicjuje XmlArrayAttribute nowe wystąpienie klasy i określa nazwę elementu XML wygenerowaną w wystąpieniu dokumentu XML.

Właściwości

ElementName

Pobiera lub ustawia nazwę elementu XML nadaną tablicy serializowanej.

Form

Pobiera lub ustawia wartość wskazującą, czy nazwa elementu XML wygenerowana przez XmlSerializer element jest kwalifikowana, czy niekwalifikowana.

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 elementu XML.

Order

Pobiera lub ustawia jawną kolejność, w której elementy są serializowane lub deserializowane.

TypeId

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

(Odziedziczone po Attribute)

Metody

Equals(Object)

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

(Odziedziczone po Attribute)
GetHashCode()

Zwraca wartość skrótu dla tego wystąpienia.

(Odziedziczone po Attribute)
GetType()

Type Pobiera wartość bieżącego wystąpienia.

(Odziedziczone po Object)
IsDefaultAttribute()

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

(Odziedziczone po Attribute)
Match(Object)

Po przesłonięciu 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 Objectelementu .

(Odziedziczone po Object)
ToString()

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

(Odziedziczone po Object)

Jawne implementacje interfejsu

_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 dla obiektu, który może służyć do pobierania 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)

Umożliwia dostęp do właściwości i metod udostępnianych przez obiekt.

(Odziedziczone po Attribute)

Dotyczy

Zobacz też