XmlArrayAttribute XmlArrayAttribute XmlArrayAttribute XmlArrayAttribute Class

Definition

Gibt an, dass XmlSerializer ein spezieller Klassenmember als Array von XML-Elementen serialisieren muss.Specifies that the XmlSerializer must serialize a particular class member as an array of XML elements.

public ref class XmlArrayAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.ReturnValue, AllowMultiple=false)]
[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.ReturnValue)]
public class XmlArrayAttribute : Attribute
type XmlArrayAttribute = class
    inherit Attribute
Public Class XmlArrayAttribute
Inherits Attribute
Vererbung
XmlArrayAttributeXmlArrayAttributeXmlArrayAttributeXmlArrayAttribute
Attribute

Beispiele

Im folgenden Beispiel wird eine Klasseninstanz in ein XML-Dokument serialisiert, das mehrere Objekt Arrays enthält.The following example serializes a class instance into an XML document that contains several object arrays. XmlArrayAttribute Wird auf die Member angewendet, die XML-Element Arrays werden.The XmlArrayAttribute is applied to the members that become XML element arrays.

#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

Hinweise

Der XmlArrayAttribute gehört zu einer Gruppe von Attributen, die steuert, XmlSerializer wie ein Objekt serialisiert oder deserialisiert.The XmlArrayAttribute belongs to a family of attributes that controls how the XmlSerializer serializes or deserializes an object. Eine umfassende Liste mit ähnlichen Attributen finden Sie unter Attribute, die die XML-Serialisierung steuern.For a complete list of similar attributes, see Attributes That Control XML Serialization.

Sie können das XmlArrayAttribute auf ein öffentliches Feld oder eine Lese-/Schreibeigenschaft anwenden, das ein Array von-Objekten zurückgibt.You can apply the XmlArrayAttribute to a public field or read/write property that returns an array of objects. Sie können Sie auch auf Auflistungen und Felder anwenden, ArrayList die ein oder ein beliebiges Feld zurückgeben, IEnumerable das ein Objekt zurückgibt, das die-SchnittstelleYou can also apply it to collections and fields that return an ArrayList or any field that returns an object that implements the IEnumerable interface.

Wenn Sie das XmlArrayAttribute auf einen Klassenmember anwenden, Serialize generiert die- XmlSerializer Methode der-Klasse eine von diesem Member generierte Sequenz von XML-Elementen.When you apply the XmlArrayAttribute to a class member, the Serialize method of the XmlSerializer class generates a nested sequence of XML elements from that member. Ein XML-Schema Dokument (eine XSD-Datei) gibt ein solches Array als complexTypean.An XML schema document (an .xsd file), indicates such an array as a complexType. Wenn z. b. die zu serialisierende Klasse eine Bestellung darstellt, können Sie ein Array erworbener Elemente generieren, indem Sie XmlArrayAttribute auf ein öffentliches Feld anwenden, das ein Array von-Objekten zurückgibt, die Bestell Elemente darstellen.For example, if the class to be serialized represents a purchase order, you can generate an array of purchased items by applying the XmlArrayAttribute to a public field that returns an array of objects that represent order items.

Wenn keine Attribute auf ein öffentliches Feld oder eine öffentliche Eigenschaft angewendet werden, die ein Array komplexer oder primitiver Typobjekte XmlSerializer zurückgibt, generiert standardmäßig eine in einem Format generierte Sequenz von XML-Elementen.If no attributes are applied to a public field or property that returns an array of complex or primitive type objects, the XmlSerializer generates a nested sequence of XML elements by default. Wenn Sie genauer steuern möchten, welche XML-Elemente generiert werden XmlArrayItemAttribute , wenden XmlArrayAttribute Sie eine und eine auf das Feld oder die Eigenschaft an.To more precisely control what XML elements are generated, apply an XmlArrayItemAttribute and an XmlArrayAttribute to the field or property. Der Name des generierten XML-Elements wird z. b. standardmäßig von der Element Kennung abgeleitet. Sie können den Namen des generierten XML-Elements ändern, indem ElementName Sie die-Eigenschaft festlegen.For example, by default, the name of the generated XML element is derived from the member identifier You can change the name of the generated XML element by setting the ElementName property.

Wenn Sie ein Array serialisieren, das Elemente eines bestimmten Typs und alle von diesem Typ abgeleiteten Klassen enthält, müssen Sie verwenden XmlArrayItemAttribute , um jeden der Typen zu deklarieren.If you serialize an array that contains items of a specific type and all the classes derived from that type, you must use the XmlArrayItemAttribute to declare each of the types.

Hinweis

Sie können in XmlArray Ihrem Code anstelle der längeren XmlArrayAttributeverwenden.You can use XmlArray in your code instead of the longer XmlArrayAttribute.

Weitere Informationen zum Verwenden von Attributen finden Sie unter Attribute.For more information about using attributes, see Attributes.

Konstruktoren

XmlArrayAttribute() XmlArrayAttribute() XmlArrayAttribute() XmlArrayAttribute()

Initialisiert eine neue Instanz der XmlArrayAttribute-Klasse.Initializes a new instance of the XmlArrayAttribute class.

XmlArrayAttribute(String) XmlArrayAttribute(String) XmlArrayAttribute(String) XmlArrayAttribute(String)

Initialisiert eine neue Instanz der XmlArrayAttribute-Klasse und gibt den in der XML-Dokumentinstanz generierten XML-Elementnamen an.Initializes a new instance of the XmlArrayAttribute class and specifies the XML element name generated in the XML document instance.

Eigenschaften

ElementName ElementName ElementName ElementName

Ruft den für das serialisierte Array angegebenen XML-Elementnamen ab oder legt diesen fest.Gets or sets the XML element name given to the serialized array.

Form Form Form Form

Ruft einen Wert ab, der angibt, ob der von XmlSerializer generierte XML-Elementname gekennzeichnet oder nicht gekennzeichnet ist, oder legt diesen fest.Gets or sets a value that indicates whether the XML element name generated by the XmlSerializer is qualified or unqualified.

IsNullable IsNullable IsNullable IsNullable

Ruft einen Wert ab, der angibt, ob XmlSerializer einen Member als leeres XML-Tag, bei dem das xsi:nil-Attribut auf true festgelegt ist, serialisieren muss, oder legt diesen fest.Gets or sets a value that indicates whether the XmlSerializer must serialize a member as an empty XML tag with the xsi:nil attribute set to true.

Namespace Namespace Namespace Namespace

Ruft den Namespace des XML-Elements ab oder legt diesen fest.Gets or sets the namespace of the XML element.

Order Order Order Order

Ruft die explizite Reihenfolge ab, in der die Elemente serialisiert oder deserialisiert werden, oder legt diese fest.Gets or sets the explicit order in which the elements are serialized or deserialized.

TypeId TypeId TypeId TypeId

Ruft bei Implementierung in einer abgeleiteten Klasse einen eindeutigen Bezeichner für dieses Attribute ab.When implemented in a derived class, gets a unique identifier for this Attribute.

(Inherited from Attribute)

Methoden

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Gibt einen Wert zurück, der angibt, ob diese Instanz gleich einem angegebenen Objekt ist.Returns a value that indicates whether this instance is equal to a specified object.

(Inherited from Attribute)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Gibt den Hashcode für diese Instanz zurück.Returns the hash code for this instance.

(Inherited from Attribute)
GetType() GetType() GetType() GetType()

Ruft den Type der aktuellen Instanz ab.Gets the Type of the current instance.

(Inherited from Object)
IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute()

Gibt beim Überschreiben in einer abgeleiteten Klasse an, ob der Wert der Instanz der Standardwert für die abgeleitete Klasse ist.When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.

(Inherited from Attribute)
Match(Object) Match(Object) Match(Object) Match(Object)

Beim Überschreiben in einer abgeleiteten Klasse wird ein Wert zurückgegeben, der angibt, ob diese Instanz einem bestimmten Objekt entspricht.When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(Inherited from Attribute)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Erstellt eine flache Kopie des aktuellen Object.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

Gibt eine Zeichenfolge zurück, die das aktuelle Objekt darstellt.Returns a string that represents the current object.

(Inherited from Object)

Explizite Schnittstellenimplementierungen

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

Ordnet eine Reihe von Namen einer entsprechenden Reihe von Dispatchbezeichnern zu.Maps a set of names to a corresponding set of dispatch identifiers.

(Inherited from Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Ruft die Typinformationen für ein Objekt ab, mit deren Hilfe die Typinformationen für eine Schnittstelle abgerufen werden können.Retrieves the type information for an object, which can be used to get the type information for an interface.

(Inherited from Attribute)
_Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32)

Ruft die Anzahl der Schnittstellen mit Typinformationen ab, die von einem Objekt bereitgestellt werden (0 oder 1).Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(Inherited from Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Stellt den Zugriff auf von einem Objekt verfügbar gemachte Eigenschaften und Methoden bereit.Provides access to properties and methods exposed by an object.

(Inherited from Attribute)

Gilt für:

Siehe auch