XmlArrayAttribute-Klasse
Gibt an, dass XmlSerializer ein spezieller Klassenmember als Array von XML-Elementen serialisieren muss.
Namespace: System.Xml.Serialization
Assembly: System.Xml (in system.xml.dll)
Syntax
'Declaration
<AttributeUsageAttribute(AttributeTargets.Property Or AttributeTargets.Field Or AttributeTargets.Parameter Or AttributeTargets.ReturnValue, AllowMultiple:=False)> _
Public Class XmlArrayAttribute
Inherits Attribute
'Usage
Dim instance As XmlArrayAttribute
[AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field|AttributeTargets.Parameter|AttributeTargets.ReturnValue, AllowMultiple=false)]
public class XmlArrayAttribute : Attribute
[AttributeUsageAttribute(AttributeTargets::Property|AttributeTargets::Field|AttributeTargets::Parameter|AttributeTargets::ReturnValue, AllowMultiple=false)]
public ref class XmlArrayAttribute : public Attribute
/** @attribute AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field|AttributeTargets.Parameter|AttributeTargets.ReturnValue, AllowMultiple=false) */
public class XmlArrayAttribute extends Attribute
AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field|AttributeTargets.Parameter|AttributeTargets.ReturnValue, AllowMultiple=false)
public class XmlArrayAttribute extends Attribute
Hinweise
XmlArrayAttribute gehört zu einer Familie von Attributen, die das Serialisieren bzw. Deserialisieren eines Objekts durch XmlSerializer steuern. Eine vollständige Liste ähnlicher Attribute finden Sie unter Attribute für die Steuerung der XML-Serialisierung.
Sie können XmlArrayAttribute auf ein öffentliches Feld oder eine Lese-/Schreibeigenschaft anwenden, das bzw. die ein Array von Objekten zurückgibt. Sie können es auch auf Auflistungen anwenden sowie auf Felder, die ArrayList zurückgeben, oder auf alle Felder, die ein Objekt zurückgeben, das die IEnumerable-Schnittstelle implementiert.
Wenn Sie XmlArrayAttribute einem Klassenmember zuweisen, generiert die Serialize-Methode der XmlSerializer-Klasse aus diesem Member eine geschachtelte Sequenz von XML-Elementen. Ein XML-Schemadokument (eine XSD-Datei) kennzeichnet ein Array dieser Art als complexType. Wenn die zu serialisierende Klasse z. B. einen Bestellschein darstellt, können Sie ein Array der bestellten Artikel generieren, indem Sie XmlArrayAttribute einem öffentlichen Feld zuweisen, das ein Array von Objekten zurückgibt, die bestellte Artikel darstellen.
Wenn öffentlichen Feldern oder Eigenschaften, die ein Array von Objekten komplexen oder primitiven Typs zurückgeben, keine Attribute zugewiesen sind, generiert XmlSerializer standardmäßig eine geschachtelte Sequenz von XML-Elementen. Um genauer steuern zu können, welche XML-Elemente generiert werden, weisen Sie dem Feld oder der Eigenschaft ein XmlArrayItemAttribute und ein XmlArrayAttribute zu. Der Name des generierten XML-Elements wird z. B. standardmäßig vom Memberbezeichner abgeleitet. Sie können den Namen des generierten XML-Elements ändern, indem Sie die ElementName-Eigenschaft festlegen.
Wenn Sie ein Array serialisieren, das Elemente eines bestimmten Typs und alle von diesem Typ abgeleiteten Klassen enthält, müssen Sie jeden dieser Typen mit XmlArrayItemAttribute deklarieren.
Hinweis
Sie können XmlArray anstelle des längeren XmlArrayAttribute im Code verwenden.
Weitere Informationen über das Verwenden von Attributen finden Sie unter Erweitern von Metadaten mithilfe von Attributen.
Beispiel
Im folgenden Beispiel wird die Instanz einer Klasse in ein XML-Dokument serialisiert, das mehrere Objektarrays enthält. XmlArrayAttribute wird auf die Member angewendet, die zu Arrays von XML-Elementen werden.
Option Explicit
Option Strict
Imports System
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
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;
}
#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" );
}
import System.*;
import System.IO.*;
import System.Xml.Serialization.*;
import System.Xml.*;
public class Run
{
public static void main(String[] args)
{
Run test = new Run();
test.SerializeDocument("books.xml");
} //main
public void SerializeDocument(String fileName)
{
// Creates a new XmlSerializer.
XmlSerializer s = new XmlSerializer(MyRootClass.class.ToType());
// 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 = Convert.ToDecimal(231);
item1.itemQuantity = 3;
item2.itemCode = "w2";
item2.itemPrice = Convert.ToDecimal(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.set_Items(myItems);
/* Serializes the class, writes it to disk, and closes
the TextWriter.
*/
s.Serialize(myWriter, myRootClass);
myWriter.Close();
} //SerializeDocument
} //Run
// 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.
*/
/** @attribute 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.
*/
/** @attribute XmlArrayItem(ElementName = "Item", IsNullable = true,
Type = Item.class, Namespace = "http://www.cpandl.com")
@attribute XmlArrayItem(ElementName = "BookItem", IsNullable = true,
Type = BookItem.class, Namespace = "http://www.cohowinery.com")
*/
/** @attribute XmlArray()
*/
/** @property
*/
public Item[] get_Items()
{
return items;
} //get_Items
/** @property
*/
public void set_Items(Item[] value)
{
items = value;
} //set_Items
} //MyRootClass
public class Item
{
/** @attribute XmlElement(ElementName = "OrderItem")
*/
public String itemName;
public String itemCode;
public System.Decimal itemPrice;
public int itemQuantity;
} //Item
public class BookItem extends Item
{
public String title;
public String author;
public String isbn;
} //BookItem
Vererbungshierarchie
System.Object
System.Attribute
System.Xml.Serialization.XmlArrayAttribute
Threadsicherheit
Alle öffentlichen statischen (Shared in Visual Basic) Member dieses Typs sind threadsicher. Bei Instanzmembern ist die Threadsicherheit nicht gewährleistet.
Plattformen
Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile für Pocket PC, Windows Mobile für Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
.NET Framework unterstützt nicht alle Versionen sämtlicher Plattformen. Eine Liste der unterstützten Versionen finden Sie unter Systemanforderungen.
Versionsinformationen
.NET Framework
Unterstützt in: 2.0, 1.1, 1.0
.NET Compact Framework
Unterstützt in: 2.0, 1.0
Siehe auch
Referenz
XmlArrayAttribute-Member
System.Xml.Serialization-Namespace
XmlArray
XmlArrayItemAttribute
XmlAttributeOverrides
XmlAttributes
XmlAttributes
Weitere Ressourcen
Einführung in die XML-Serialisierung
Gewusst wie: Angeben eines alternativen Elementnamens für einen XML-Stream
Steuern der XML-Serialisierung mit Attributen
Beispiele für die XML-Serialisierung
XML Schema Definition-Tool (Xsd.exe)