XmlArrayAttribute Osztály

Definíció

Megadja, hogy az XmlSerializer adott osztálytagot XML-elemek tömbjeként kell szerializálnia.

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
Öröklődés
XmlArrayAttribute
Attribútumok

Példák

Az alábbi példa egy osztálypéldányt több objektumtömböt tartalmazó XML-dokumentumba szerializál. Ez XmlArrayAttribute az XML-elemtömbökké váló tagokra lesz alkalmazva.

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

Megjegyzések

Az XmlArrayAttribute attribútumcsalád az objektum szerializálásának vagy deszerializálásának módját szabályozza XmlSerializer . A hasonló attribútumok teljes listáját az XML-szerializálást vezérlő attribútumok című témakörben találja.

Ezt alkalmazhatja XmlArrayAttribute egy olyan nyilvános mezőre vagy írási/olvasási tulajdonságra, amely egy objektumtömböt ad vissza. Olyan gyűjteményekre és mezőkre is alkalmazhatja, amelyek egy ArrayList vagy bármely olyan mezőt ad vissza, amely az interfészt megvalósító IEnumerable objektumot ad vissza.

Amikor egy osztálytagra alkalmazza az XmlArrayAttribute osztályt, az SerializeXmlSerializer osztály metódusa xml-elemek beágyazott sorozatát hozza létre az adott tagból. Az XML-sémadokumentum (.xsd fájl) egy ilyen tömböt complexTypejelöl. Ha például a szerializálandó osztály egy beszerzési rendelést jelöl, akkor a megvásárolt cikkek tömbje úgy hozható létre, hogy egy olyan nyilvános mezőre alkalmazza XmlArrayAttribute , amely a rendeléselemeket képviselő objektumtömböt adja vissza.

Ha a rendszer nem alkalmaz attribútumokat egy olyan nyilvános mezőre vagy tulajdonságra, amely összetett vagy primitív típusú objektumokat tartalmazó tömböt ad vissza, a XmlSerializer rendszer alapértelmezés szerint xml-elemek beágyazott sorozatát hozza létre. A létrehozott XML-elemek pontosabb szabályozásához alkalmazzon egy és egy XmlArrayItemAttributeXmlArrayAttribute elemet a mezőre vagy a tulajdonságra. Alapértelmezés szerint például a létrehozott XML-elem neve a tagazonosítóból származik. A létrehozott XML-elem nevét a tulajdonság beállításával ElementName módosíthatja.

Ha olyan tömböt szerializál, amely egy adott típusú elemeket és az ebből a típusból származtatott összes osztályt tartalmaz, az egyes típusok deklarálásához az XmlArrayItemAttribute adott tömböt kell használnia.

Note

XmlArray A hosszabb XmlArrayAttributehelyett használhatja a kódban.

Az attribútumok használatáról további információt az Attribútumok című témakörben talál.

Konstruktorok

Name Description
XmlArrayAttribute()

Inicializálja a XmlArrayAttribute osztály új példányát.

XmlArrayAttribute(String)

Inicializálja az XmlArrayAttribute osztály új példányát, és megadja az XML-dokumentumpéldányban létrehozott XML-elem nevét.

Tulajdonságok

Name Description
ElementName

Lekéri vagy beállítja a szerializált tömbhöz megadott XML-elemnevet.

Form

Lekéri vagy beállít egy értéket, amely jelzi, hogy az XML-elem által XmlSerializer létrehozott név minősített vagy nem minősített-e.

IsNullable

Lekéri vagy beállít egy értéket, amely jelzi, hogy a XmlSerializer tagnak üres XML-címkeként kell-e szerializálnia egy tagot, és az attribútum értéke a xsi:nil következő true.

Namespace

Lekéri vagy beállítja az XML-elem névterét.

Order

Lekéri vagy beállítja az elemek szerializálásának vagy deszerializálásának explicit sorrendjét.

TypeId

Ha származtatott osztályban implementálják, ehhez egy egyedi azonosítót Attributekap.

(Öröklődés forrása Attribute)

Metódusok

Name Description
Equals(Object)

Olyan értéket ad vissza, amely jelzi, hogy ez a példány egyenlő-e egy adott objektummal.

(Öröklődés forrása Attribute)
GetHashCode()

A példány kivonatkódját adja vissza.

(Öröklődés forrása Attribute)
GetType()

Lekéri az Type aktuális példányt.

(Öröklődés forrása Object)
IsDefaultAttribute()

Ha egy származtatott osztályban felül van bírálva, azt jelzi, hogy a példány értéke-e a származtatott osztály alapértelmezett értéke.

(Öröklődés forrása Attribute)
Match(Object)

Származtatott osztály felülírásakor egy olyan értéket ad vissza, amely jelzi, hogy ez a példány egy adott objektummal egyenlő-e.

(Öröklődés forrása Attribute)
MemberwiseClone()

Az aktuális Objectpéldány sekély másolatát hozza létre.

(Öröklődés forrása Object)
ToString()

Az aktuális objektumot jelképező sztringet ad vissza.

(Öröklődés forrása Object)

Explicit interfész-implementációk

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

Névkészletet képez le a küldési azonosítók megfelelő készletére.

(Öröklődés forrása Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Lekéri egy objektum típusadatait, amelyek a felület típusadatainak lekérésére használhatók.

(Öröklődés forrása Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Lekéri az objektumok által biztosított típusinformációs felületek számát (0 vagy 1).

(Öröklődés forrása Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Hozzáférést biztosít az objektumok által közzétett tulajdonságokhoz és metódusokhoz.

(Öröklődés forrása Attribute)

A következőre érvényes:

Lásd még