영어로 읽기

다음을 통해 공유


XmlArrayAttribute 클래스

XmlSerializer가 특정 클래스 멤버를 XML 요소의 배열로 serialize하도록 지정합니다.

네임스페이스: System.Xml.Serialization
어셈블리: System.Xml(system.xml.dll)

구문

‘선언
<AttributeUsageAttribute(AttributeTargets.Property Or AttributeTargets.Field Or AttributeTargets.Parameter Or AttributeTargets.ReturnValue, AllowMultiple:=False)> _
Public Class XmlArrayAttribute
    Inherits Attribute
‘사용 방법
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

설명

XmlSerializer가 개체를 serialize 및 deserialize하는 방식을 제어하는 특성 패밀리에 속한 XmlArrayAttribute입니다. 유사한 특성에 대한 전체 목록은 XML Serialization을 제어하는 특성을 참조하십시오.

개체의 배열을 반환하는 공용 필드 또는 읽기/쓰기 속성에 XmlArrayAttribute를 적용할 수 있으며, 컬렉션, ArrayList를 반환하는 필드 또는 IEnumerable 인터페이스를 구현하는 개체를 반환하는 필드에도 적용할 수 있습니다.

XmlArrayAttribute를 클래스 멤버에 적용하면 XmlSerializer 클래스의 Serialize 메서드가 해당 멤버에서 XML 요소의 중첩된 시퀀스를 생성합니다. XML 스키마 문서(.xsd 파일)는 그러한 배열을 complexType으로 표현합니다. 예를 들어, serialize될 클래스가 구매 주문서를 나타내는 경우, 주문 항목을 나타내는 개체로 이루어진 배열을 반환하는 공용 필드에 XmlArrayAttribute를 적용하면 구매한 항목의 배열을 생성할 수 있습니다.

복합 형식 또는 기본 형식 개체로 이루어진 배열을 반환하는 공용 필드나 속성에 특성을 적용하지 않으면 XmlSerializer는 기본적으로 XML 요소의 중첩된 시퀀스를 생성합니다. 생성되는 XML 요소를 더욱 정확히 제어하려면 필드 또는 속성에 XmlArrayItemAttributeXmlArrayAttribute를 적용하십시오. 예를 들어, 생성된 XML 요소의 이름은 기본적으로 멤버 식별자에서 파생되므로 ElementName 속성을 설정하여 생성된 XML 요소의 이름을 변경할 수 있습니다.

특정한 형식의 항목 및 해당 형식에서 파생된 모든 클래스를 포함하는 배열을 serialize하는 경우 XmlArrayItemAttribute를 사용하여 각 형식을 선언해야 합니다.

참고

XmlArrayAttribute 대신 XmlArray를 코드에서 사용할 수 있습니다.

특성 사용에 대한 자세한 내용은 특성을 사용하여 메타데이터 확장을 참조하십시오.

예제

다음 예제에서는 클래스 인스턴스가 개체 배열이 여러 개 포함된 XML 문서로 serialize됩니다. XmlArrayAttribute는 XML 요소로 이루어진 배열이 되는 멤버에 적용됩니다.

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

상속 계층 구조

System.Object
   System.Attribute
    System.Xml.Serialization.XmlArrayAttribute

스레드로부터의 안전성

이 형식의 모든 public static(Visual Basic의 경우 Shared) 멤버는 스레드로부터 안전합니다. 인터페이스 멤버는 스레드로부터 안전하지 않습니다.

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0, 1.0에서 지원

참고 항목

참조

XmlArrayAttribute 멤버
System.Xml.Serialization 네임스페이스
XmlArray
XmlArrayItemAttribute
XmlAttributeOverrides
XmlAttributes
XmlAttributes

기타 리소스

XML Serialization 소개
방법: XML 스트림의 대체 요소 이름 지정
특성을 사용하여 XML Serialization 제어
XML Serialization 예
XML 스키마 정의 도구(Xsd.exe)