XmlArrayAttribute Classe
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Specifica che il XmlSerializer deve serializzare un membro di classe specifico come matrice di elementi 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
- Ereditarietà
- Attributi
Esempio
Nell'esempio seguente viene serializzata un'istanza di classe in un documento XML contenente diverse matrici di oggetti. Viene XmlArrayAttribute applicato ai membri che diventano matrici di elementi 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
Commenti
Appartiene XmlArrayAttribute a una famiglia di attributi che controlla la XmlSerializer modalità di serializzazione o deserializzazione di un oggetto. Per un elenco completo di attributi simili, vedere Attributi che controllano la serializzazione XML.
È possibile applicare a XmlArrayAttribute un campo pubblico o a una proprietà di lettura/scrittura che restituisce una matrice di oggetti. È anche possibile applicarlo alle raccolte e ai campi che restituiscono un ArrayList oggetto o qualsiasi campo che restituisce un oggetto che implementa l'interfaccia IEnumerable .
Quando si applica a XmlArrayAttribute un membro di classe, il Serialize metodo della XmlSerializer classe genera una sequenza nidificata di elementi XML da tale membro. Un documento XML Schema (un file con estensione xsd), indica una matrice di questo tipo come complexType. Ad esempio, se la classe da serializzare rappresenta un ordine di acquisto, è possibile generare una matrice di articoli acquistati applicando a XmlArrayAttribute un campo pubblico che restituisce una matrice di oggetti che rappresentano gli articoli degli ordini.
Se non vengono applicati attributi a un campo pubblico o a una proprietà che restituisce una matrice di oggetti di tipo complesso o primitivo, genera XmlSerializer una sequenza annidata di elementi XML per impostazione predefinita. Per controllare in modo più preciso gli elementi XML generati, applicare un oggetto XmlArrayItemAttribute e un XmlArrayAttribute oggetto al campo o alla proprietà . Per impostazione predefinita, ad esempio, il nome dell'elemento XML generato deriva dall'identificatore del membro È possibile modificare il nome dell'elemento XML generato impostando la ElementName proprietà .
Se si serializza una matrice che contiene elementi di un tipo specifico e tutte le classi derivate da tale tipo, è necessario utilizzare per XmlArrayItemAttribute dichiarare ognuno dei tipi.
Annotazioni
È possibile usare XmlArray nel codice anziché più lungo XmlArrayAttribute.
Per altre informazioni sull'uso degli attributi, vedere Attributi.
Costruttori
| Nome | Descrizione |
|---|---|
| XmlArrayAttribute() |
Inizializza una nuova istanza della classe XmlArrayAttribute. |
| XmlArrayAttribute(String) |
Inizializza una nuova istanza della XmlArrayAttribute classe e specifica il nome dell'elemento XML generato nell'istanza del documento XML. |
Proprietà
| Nome | Descrizione |
|---|---|
| ElementName |
Ottiene o imposta il nome dell'elemento XML assegnato alla matrice serializzata. |
| Form |
Ottiene o imposta un valore che indica se il nome dell'elemento XmlSerializer XML generato da è qualificato o non qualificato. |
| IsNullable |
Ottiene o imposta un valore che indica se deve XmlSerializer serializzare un membro come tag XML vuoto con l'attributo |
| Namespace |
Ottiene o imposta lo spazio dei nomi dell'elemento XML. |
| Order |
Ottiene o imposta l'ordine esplicito in cui gli elementi vengono serializzati o deserializzati. |
| TypeId |
Se implementato in una classe derivata, ottiene un identificatore univoco per questo Attribute. (Ereditato da Attribute) |
Metodi
| Nome | Descrizione |
|---|---|
| Equals(Object) |
Restituisce un valore che indica se questa istanza è uguale a un oggetto specificato. (Ereditato da Attribute) |
| GetHashCode() |
Restituisce il codice hash per questa istanza. (Ereditato da Attribute) |
| GetType() |
Ottiene il Type dell'istanza corrente. (Ereditato da Object) |
| IsDefaultAttribute() |
Quando sottoposto a override in una classe derivata, indica se il valore di questa istanza è il valore predefinito per la classe derivata. (Ereditato da Attribute) |
| Match(Object) |
Quando sottoposto a override in una classe derivata, restituisce un valore che indica se questa istanza è uguale a un oggetto specificato. (Ereditato da Attribute) |
| MemberwiseClone() |
Crea una copia superficiale del Objectcorrente. (Ereditato da Object) |
| ToString() |
Restituisce una stringa che rappresenta l'oggetto corrente. (Ereditato da Object) |
Implementazioni dell'interfaccia esplicita
| Nome | Descrizione |
|---|---|
| _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Esegue il mapping di un set di nomi a un set corrispondente di ID dispatch. (Ereditato da Attribute) |
| _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
Recupera le informazioni sul tipo per un oggetto, che può essere utilizzato per ottenere le informazioni sul tipo per un'interfaccia. (Ereditato da Attribute) |
| _Attribute.GetTypeInfoCount(UInt32) |
Recupera il numero delle interfacce di informazioni sul tipo fornite da un oggetto (0 o 1). (Ereditato da Attribute) |
| _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Fornisce l'accesso alle proprietà e ai metodi esposti da un oggetto . (Ereditato da Attribute) |