XmlElementAttribute 클래스

정의

공용 필드 또는 속성을 포함하는 개체를 XmlSerializer가 직렬화하거나 역직렬화할 때 해당 필드나 속성이 XML 요소를 나타냄을 의미합니다.

public ref class XmlElementAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.ReturnValue, AllowMultiple=true)]
public class XmlElementAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.ReturnValue, AllowMultiple=true)>]
type XmlElementAttribute = class
    inherit Attribute
Public Class XmlElementAttribute
Inherits Attribute
상속
XmlElementAttribute
특성

예제

다음 예제에서는 명명 Group 된 클래스를 직렬화하고 여러 멤버에 적용합니다 XmlElementAttribute . 명명된 Employees 필드는 개체 배열 Employee 을 반환합니다. 이 경우 XmlElementAttribute 결과 XML이 중첩되지 않도록 지정합니다(배열에 있는 항목의 기본 동작).

#using <System.Xml.dll>
#using <System.dll>

using namespace System;
using namespace System::Collections;
using namespace System::IO;
using namespace System::Xml::Serialization;
public ref class Employee
{
public:
   String^ Name;
};

public ref class Manager: public Employee
{
public:
   int Level;
};

public ref class Group
{
public:

   /* Set the element name and namespace of the XML element.
      By applying an XmlElementAttribute to an array,  you instruct
      the XmlSerializer to serialize the array as a series of XML
      elements, instead of a nested set of elements. */

   [XmlElement(
   ElementName="Members",
   Namespace="http://www.cpandl.com")]
   array<Employee^>^Employees;

   [XmlElement(DataType="snippet1>",
   ElementName="Building")]
   double GroupID;

   [XmlElement(DataType="hexBinary")]
   array<Byte>^HexBytes;

   [XmlElement(DataType="boolean")]
   bool IsActive;

   [XmlElement(Type=::Manager::typeid)]
   Employee^ Manager;

   [XmlElement(Int32::typeid,
   ElementName="ObjectNumber"),
   XmlElement(String::typeid,
   ElementName="ObjectString")]
   ArrayList^ ExtraInfo;
};

void SerializeObject( String^ filename )
{
   // Create the XmlSerializer.
   XmlSerializer^ s = gcnew XmlSerializer( Group::typeid );

   // To write the file, a TextWriter is required.
   TextWriter^ writer = gcnew StreamWriter( filename );

   /* Create an instance of the group to serialize, and set
      its properties. */
   Group^ group = gcnew Group;
   group->GroupID = 10.089f;
   group->IsActive = false;
   array<Byte>^temp0 = {Convert::ToByte( 100 )};
   group->HexBytes = temp0;
   Employee^ x = gcnew Employee;
   Employee^ y = gcnew Employee;
   x->Name = "Jack";
   y->Name = "Jill";
   array<Employee^>^temp1 = {x,y};
   group->Employees = temp1;
   Manager^ mgr = gcnew Manager;
   mgr->Name = "Sara";
   mgr->Level = 4;
   group->Manager = mgr;

   /* Add a number and a string to the 
      ArrayList returned by the ExtraInfo property. */
   group->ExtraInfo = gcnew ArrayList;
   group->ExtraInfo->Add( 42 );
   group->ExtraInfo->Add( "Answer" );

   // Serialize the object, and close the TextWriter.      
   s->Serialize( writer, group );
   writer->Close();
}

void DeserializeObject( String^ filename )
{
   FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
   XmlSerializer^ x = gcnew XmlSerializer( Group::typeid );
   Group^ g = dynamic_cast<Group^>(x->Deserialize( fs ));
   Console::WriteLine( g->Manager->Name );
   Console::WriteLine( g->GroupID );
   Console::WriteLine( g->HexBytes[ 0 ] );
   IEnumerator^ myEnum = g->Employees->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Employee^ e = safe_cast<Employee^>(myEnum->Current);
      Console::WriteLine( e->Name );
   }
}

int main()
{
   SerializeObject( "FirstDoc.xml" );
   DeserializeObject( "FirstDoc.xml" );
}
using System;
using System.Collections;
using System.IO;
using System.Xml.Serialization;

public class Group
{
   /* Set the element name and namespace of the XML element.
   By applying an XmlElementAttribute to an array,  you instruct
   the XmlSerializer to serialize the array as a series of XML
   elements, instead of a nested set of elements. */

   [XmlElement(
   ElementName = "Members",
   Namespace = "http://www.cpandl.com")]
   public Employee[] Employees;

   [XmlElement(DataType = "double",
   ElementName = "Building")]
   public double GroupID;

   [XmlElement(DataType = "hexBinary")]
   public byte [] HexBytes;

   [XmlElement(DataType = "boolean")]
   public bool IsActive;

   [XmlElement(Type = typeof(Manager))]
   public Employee Manager;

   [XmlElement(typeof(int),
   ElementName = "ObjectNumber"),
   XmlElement(typeof(string),
   ElementName = "ObjectString")]
   public ArrayList ExtraInfo;
}

public class Employee
{
   public string Name;
}

public class Manager:Employee{
   public int Level;
}

public class Run
{
    public static void Main()
    {
       Run test = new Run();
       test.SerializeObject("FirstDoc.xml");
       test.DeserializeObject("FirstDoc.xml");
    }

   public void SerializeObject(string filename)
   {
      // Create the XmlSerializer.
      XmlSerializer s = new XmlSerializer(typeof(Group));

      // To write the file, a TextWriter is required.
      TextWriter writer = new StreamWriter(filename);

      /* Create an instance of the group to serialize, and set
         its properties. */
      Group group = new Group();
      group.GroupID = 10.089f;
      group.IsActive = false;

      group.HexBytes = new byte[1]{Convert.ToByte(100)};

      Employee x = new Employee();
      Employee y = new Employee();

      x.Name = "Jack";
      y.Name = "Jill";

      group.Employees = new Employee[2]{x,y};

      Manager mgr = new Manager();
      mgr.Name = "Sara";
      mgr.Level = 4;
      group.Manager = mgr;

      /* Add a number and a string to the
      ArrayList returned by the ExtraInfo property. */
      group.ExtraInfo = new ArrayList();
      group.ExtraInfo.Add(42);
      group.ExtraInfo.Add("Answer");

      // Serialize the object, and close the TextWriter.
      s.Serialize(writer, group);
      writer.Close();
   }

   public void DeserializeObject(string filename)
   {
      FileStream fs = new FileStream(filename, FileMode.Open);
      XmlSerializer x = new XmlSerializer(typeof(Group));
      Group g = (Group) x.Deserialize(fs);
      Console.WriteLine(g.Manager.Name);
      Console.WriteLine(g.GroupID);
      Console.WriteLine(g.HexBytes[0]);
      foreach(Employee e in g.Employees)
      {
         Console.WriteLine(e.Name);
      }
   }
}
Imports System.Collections
Imports System.IO
Imports System.Xml.Serialization


Public Class Group
    ' Set the element name and namespace of the XML element.
    <XmlElement(ElementName := "Members", _
     Namespace := "http://www.cpandl.com")> _    
    Public Employees() As Employee
    
    <XmlElement(DataType := "double", _
     ElementName := "Building")> _
    Public GroupID As Double
    
    <XmlElement(DataType := "hexBinary")> _
    Public HexBytes() As Byte
    
    <XmlElement(DataType := "boolean")> _
    Public IsActive As Boolean
    
    <XmlElement(GetType(Manager))> _
    Public Manager As Employee
    
    <XmlElement(GetType(Integer), _
        ElementName := "ObjectNumber"), _
     XmlElement(GetType(String), _
        ElementName := "ObjectString")> _
    Public ExtraInfo As ArrayList
End Class

Public Class Employee
    Public Name As String
End Class

Public Class Manager
    Inherits Employee
    Public Level As Integer
End Class

Public Class Run
    
    Public Shared Sub Main()
        Dim test As New Run()
        test.SerializeObject("FirstDoc.xml")
        test.DeserializeObject("FirstDoc.xml")
    End Sub
    
    Public Sub SerializeObject(filename As String)
        ' Create the XmlSerializer.
        Dim s As New XmlSerializer(GetType(Group))
        
        ' To write the file, a TextWriter is required.
        Dim writer As New StreamWriter(filename)
        
        ' Create an instance of the group to serialize, and set
        ' its properties. 
        Dim group As New Group()
        group.GroupID = 10.089f
        group.IsActive = False
        
        group.HexBytes = New Byte() {Convert.ToByte(100)}
        
        Dim x As New Employee()
        Dim y As New Employee()
        
        x.Name = "Jack"
        y.Name = "Jill"
        
        group.Employees = New Employee() {x, y}
        
        Dim mgr As New Manager()
        mgr.Name = "Sara"
        mgr.Level = 4
        group.Manager = mgr
        
        ' Add a number and a string to the
        ' ArrayList returned by the ExtraInfo property. 
        group.ExtraInfo = New ArrayList()
        group.ExtraInfo.Add(42)
        group.ExtraInfo.Add("Answer")
        
        ' Serialize the object, and close the TextWriter.      
        s.Serialize(writer, group)
        writer.Close()
    End Sub    
    
    Public Sub DeserializeObject(filename As String)
        Dim fs As New FileStream(filename, FileMode.Open)
        Dim x As New XmlSerializer(GetType(Group))
        Dim g As Group = CType(x.Deserialize(fs), Group)
        Console.WriteLine(g.Manager.Name)
        Console.WriteLine(g.GroupID)
        Console.WriteLine(g.HexBytes(0))

        Dim e As Employee
        For Each e In g.Employees
            Console.WriteLine(e.Name)
        Next e
    End Sub
End Class

설명

개체 XmlElementAttribute 를 직렬화하거나 역직렬화하는 방법을 XmlSerializer 제어하는 특성 패밀리에 속합니다. 유사한 특성의 전체 목록은 XML Serialization을 제어하는 특성을 참조하세요.

XML 문서에는 일반적으로 XML 요소가 포함되며, 각 요소는 가능한 특성이 있는 여는 태그, 닫는 태그 및 태그 간의 데이터라는 세 부분으로 구성됩니다. XML 태그는 중첩될 수 있습니다. 즉, 태그 간의 데이터도 XML 요소일 수 있습니다. 한 요소가 다른 요소를 묶을 수 있는 이 용량을 사용하면 문서에 데이터 계층 구조가 포함될 수 있습니다. XML 요소에는 특성을 포함할 수도 있습니다.

XmlElementAttribute 공용 필드 또는 공용 읽기/쓰기 속성에 적용하여 요소 이름 및 네임스페이스와 같은 XML 요소의 특성을 제어합니다.

개체 XmlElementAttribute 배열을 반환하는 필드에 여러 번 적용할 수 있습니다. 이 용도는 배열에 삽입할 수 있는 다양한 형식을 지정하는 것입니다( 속성을 통해 Type ). 예를 들어 다음 C# 코드의 배열은 문자열과 정수 모두를 허용합니다.

public class Things{  
   [XmlElement(Type = typeof(string)),  
   XmlElement(Type = typeof(int))]  
   public object[] StringsAndInts;  
}  

이렇게 하면 XML이 다음과 같을 수 있습니다.

<Things>  
   <string>Hello</string>  
   <int>999</int>  
   <string>World</string>  
</Things>  

속성 값을 지정 ElementName 하지 않고 여러 번 적용 XmlElementAttribute 하면 요소의 이름이 허용되는 개체 형식의 이름을 따서 지정됩니다.

배열을 XmlElementAttribute 반환하는 필드 또는 속성에 적용하면 배열의 항목이 XML 요소 시퀀스로 인코딩됩니다.

반면 이러한 필드 또는 속성에 적용 되지 않은 경우 XmlElementAttribute 배열의 항목 필드 또는 속성의 이름을 따서 명명 된 요소 아래에 중첩 된 요소의 시퀀스로 인코딩됩니다. (배열을 XmlArrayAttribute serialize하는 방법을 제어하려면 해당 및 XmlArrayItemAttribute 특성을 사용합니다.)

원래 필드 또는 속성의 형식, 즉 적용XmlElementAttribute한 필드 또는 속성 형식에서 파생된 형식을 지정하도록 속성을 설정할 Type 수 있습니다.

필드 또는 속성이 반환되는 ArrayList경우 멤버의 여러 인스턴스를 XmlElementAttribute 적용할 수 있습니다. 각 인스턴스에 Type 대해 속성을 배열에 삽입할 수 있는 개체 형식으로 설정합니다.

특성을 사용 하는 방법에 대 한 자세한 내용은 참조 하세요. 특성합니다.

참고

더 긴 XmlElementAttribute대신 코드에서 단어를 XmlElement 사용할 수 있습니다.

생성자

XmlElementAttribute()

XmlElementAttribute 클래스의 새 인스턴스를 초기화합니다.

XmlElementAttribute(String)

XmlElementAttribute 클래스의 새 인스턴스를 초기화하고 XML 요소의 이름을 지정합니다.

XmlElementAttribute(String, Type)

XmlElementAttribute의 새 인스턴스를 초기화하고 XML 요소의 이름을 지정하며 XmlElementAttribute가 적용되는 멤버의 파생 형식도 지정합니다. 이 멤버 형식은 XmlSerializer가 이를 포함하는 개체를 serialize할 때 사용됩니다.

XmlElementAttribute(Type)

XmlElementAttribute 클래스의 새 인스턴스를 초기화하고 XmlElementAttribute가 적용되는 멤버에 대한 형식을 지정합니다. 이 형식은 XmlSerializer가 이를 포함하는 개체를 직렬화하거나 역직렬화할 때 사용됩니다.

속성

DataType

XmlSerializer에 의해 생성된 XML 요소의 XSD(XML 스키마 정의) 데이터 형식을 가져오거나 설정합니다.

ElementName

생성된 XML 요소의 이름을 가져오거나 설정합니다.

Form

요소가 한정되었는지 여부를 나타내는 값을 가져오거나 설정합니다.

IsNullable

XmlSerializernull로 설정된 멤버를 xsi:nil 특성이 true로 설정된 빈 태그로 serialize해야 하는지 여부를 나타내는 값을 가져오거나 설정합니다.

Namespace

클래스가 serialize될 때 결과로 만들어지는 XML 요소에 할당된 네임스페이스를 가져오거나 설정합니다.

Order

요소가 직렬화 또는 역직렬화되는 명시적 순서를 가져오거나 설정합니다.

Type

XML 요소를 나타내는 데 사용되는 개체 형식을 가져오거나 설정합니다.

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)

적용 대상

추가 정보