Поделиться через


XmlArrayAttribute Класс

Определение

Указывает, что XmlSerializer должен сериализовать определенный член класса в виде массива 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
Наследование
XmlArrayAttribute
Атрибуты

Примеры

В следующем примере выполняется сериализация экземпляра класса в XML-документ, содержащий несколько массивов объектов. Он XmlArrayAttribute применяется к элементам, которые становятся массивами элементов 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

Комментарии

Относится XmlArrayAttribute к семейству атрибутов, которые управляют тем, как XmlSerializer сериализует или десериализирует объект. Полный список аналогичных атрибутов см. в разделе Атрибуты, управляющие сериализацией XML.

Можно применить XmlArrayAttribute к общедоступному полю или свойству чтения или записи, возвращающего массив объектов. Его также можно применить к коллекциям и полям, возвращающим ArrayList или любое поле, возвращающее объект, реализующий IEnumerable интерфейс.

При применении XmlArrayAttribute к члену Serialize класса метод XmlSerializer класса создает вложенную последовательность XML-элементов из этого элемента. Xml-документ схемы (XSD-файл) указывает на такой массив, как .complexType Например, если класс для сериализации представляет заказ на покупку, можно создать массив приобретенных элементов, применив XmlArrayAttribute его к общедоступному полю, который возвращает массив объектов, представляющих элементы заказа.

Если атрибуты не применяются к открытому полю или свойству, возвращающим массив сложных или примитивных объектов типов, XmlSerializer по умолчанию создается вложенная последовательность XML-элементов. Чтобы точно управлять созданными XML-элементами, примените к XmlArrayItemAttribute полю или свойству и поле XmlArrayAttribute . Например, по умолчанию имя созданного XML-элемента является производным от идентификатора члена, можно изменить имя созданного XML-элемента, задав ElementName свойство.

При сериализации массива, содержащего элементы определенного типа и все классы, производные от этого типа, необходимо использовать XmlArrayItemAttribute для объявления каждого из типов.

Замечание

Вместо более длительного XmlArrayAttributeиспользования можно использовать XmlArray в коде.

Дополнительные сведения об использовании атрибутов см. в разделе "Атрибуты".

Конструкторы

Имя Описание
XmlArrayAttribute()

Инициализирует новый экземпляр класса XmlArrayAttribute.

XmlArrayAttribute(String)

Инициализирует новый экземпляр XmlArrayAttribute класса и задает имя XML-элемента, созданное в экземпляре XML-документа.

Свойства

Имя Описание
ElementName

Возвращает или задает имя XML-элемента, заданное сериализованному массиву.

Form

Возвращает или задает значение, указывающее, является ли имя XML-элемента, созданного XmlSerializer квалифицированным или неквалифицированным.

IsNullable

Возвращает или задает значение, указывающее, должен ли XmlSerializer сериализовать элемент в виде пустого XML-тега с заданным атрибутом xsi:niltrue.

Namespace

Возвращает или задает пространство имен XML-элемента.

Order

Возвращает или задает явный порядок сериализации или десериализации элементов.

TypeId

При реализации в производном классе получает уникальный идентификатор для этого Attribute.

(Унаследовано от Attribute)

Методы

Имя Описание
Equals(Object)

Возвращает значение, указывающее, равен ли этот экземпляр указанному объекту.

(Унаследовано от Attribute)
GetHashCode()

Возвращает хэш-код для этого экземпляра.

(Унаследовано от Attribute)
GetType()

Возвращает Type текущего экземпляра.

(Унаследовано от Object)
IsDefaultAttribute()

При переопределении в производном классе указывает, является ли значение этого экземпляра значением по умолчанию для производного класса.

(Унаследовано от Attribute)
Match(Object)

При переопределении в производном классе возвращает значение, указывающее, равен ли этот экземпляр указанному объекту.

(Унаследовано от Attribute)
MemberwiseClone()

Создает неглубокую копию текущей Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Явные реализации интерфейса

Имя Описание
_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Сопоставляет набор имен соответствующему набору идентификаторов диспетчеризации.

(Унаследовано от Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Извлекает сведения о типе объекта, который можно использовать для получения сведений о типе для интерфейса.

(Унаследовано от Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Возвращает количество предоставляемых объектом интерфейсов для доступа к сведениям о типе (0 или 1).

(Унаследовано от Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Предоставляет доступ к свойствам и методам, предоставляемым объектом.

(Унаследовано от Attribute)

Применяется к

См. также раздел