XmlAttributeOverrides 클래스

정의

XmlSerializer를 사용하여 개체를 직렬화하거나 역직렬화하면 속성, 필드 및 클래스 특성을 재정의할 수 있습니다.

public ref class XmlAttributeOverrides
public class XmlAttributeOverrides
type XmlAttributeOverrides = class
Public Class XmlAttributeOverrides
상속
XmlAttributeOverrides

예제

다음 예제에서는 개체 배열 Instrument 을 반환하는 단일 필드를 포함하는 명명 Orchestra``Instruments 된 클래스를 serialize합니다. 두 번째 클래스가 Brass 에서 상속 되는 Instrument 클래스입니다. 이 예제에서는 클래스의 인스턴스를 XmlAttributeOverrides 사용하여 필드를 재정 Instrument 의하여 필드가 개체를 수락 Brass 할 수 있도록 합니다.

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

using namespace System;
using namespace System::IO;
using namespace System::Xml::Serialization;

public ref class Instrument
{
public:
   String^ Name;
};

public ref class Brass: public Instrument
{
public:
   bool IsValved;
};

public ref class Orchestra
{
public:
   array<Instrument^>^Instruments;
};

void SerializeObject( String^ filename )
{
   /* Each overridden field, property, or type requires 
      an XmlAttributes object. */
   XmlAttributes^ attrs = gcnew XmlAttributes;

   /* Create an XmlElementAttribute to override the 
      field that returns Instrument objects. The overridden field
      returns Brass objects instead. */
   XmlElementAttribute^ attr = gcnew XmlElementAttribute;
   attr->ElementName = "Brass";
   attr->Type = Brass::typeid;

   // Add the element to the collection of elements.
   attrs->XmlElements->Add( attr );

   // Create the XmlAttributeOverrides object.
   XmlAttributeOverrides^ attrOverrides = gcnew XmlAttributeOverrides;

   /* Add the type of the class that contains the overridden 
      member and the XmlAttributes to override it with to the 
      XmlAttributeOverrides object. */
   attrOverrides->Add( Orchestra::typeid, "Instruments", attrs );

   // Create the XmlSerializer using the XmlAttributeOverrides.
   XmlSerializer^ s = gcnew XmlSerializer( Orchestra::typeid,attrOverrides );

   // Writing the file requires a TextWriter.
   TextWriter^ writer = gcnew StreamWriter( filename );

   // Create the object that will be serialized.
   Orchestra^ band = gcnew Orchestra;

   // Create an object of the derived type.
   Brass^ i = gcnew Brass;
   i->Name = "Trumpet";
   i->IsValved = true;
   array<Instrument^>^myInstruments = {i};
   band->Instruments = myInstruments;

   // Serialize the object.
   s->Serialize( writer, band );
   writer->Close();
}

void DeserializeObject( String^ filename )
{
   XmlAttributeOverrides^ attrOverrides = gcnew XmlAttributeOverrides;
   XmlAttributes^ attrs = gcnew XmlAttributes;

   // Create an XmlElementAttribute to override the Instrument.
   XmlElementAttribute^ attr = gcnew XmlElementAttribute;
   attr->ElementName = "Brass";
   attr->Type = Brass::typeid;

   // Add the XmlElementAttribute to the collection of objects.
   attrs->XmlElements->Add( attr );
   attrOverrides->Add( Orchestra::typeid, "Instruments", attrs );

   // Create the XmlSerializer using the XmlAttributeOverrides.
   XmlSerializer^ s = gcnew XmlSerializer( Orchestra::typeid,attrOverrides );
   FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
   Orchestra^ band = dynamic_cast<Orchestra^>(s->Deserialize( fs ));
   Console::WriteLine( "Brass:" );

   /* The difference between deserializing the overridden 
      XML document and serializing it is this: To read the derived 
      object values, you must declare an object of the derived type 
      (Brass), and cast the Instrument instance to it. */
   Brass^ b;
   System::Collections::IEnumerator^ myEnum = band->Instruments->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Instrument^ i = safe_cast<Instrument^>(myEnum->Current);
      b = dynamic_cast<Brass^>(i);
      Console::WriteLine( "{0}\n{1}", b->Name, b->IsValved );
   }
}

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

public class Orchestra
{
   public Instrument[] Instruments;
}

public class Instrument
{
   public string Name;
}

public class Brass:Instrument
{
   public bool IsValved;
}

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

    public void SerializeObject(string filename)
    {
      /* Each overridden field, property, or type requires
      an XmlAttributes object. */
      XmlAttributes attrs = new XmlAttributes();

      /* Create an XmlElementAttribute to override the
      field that returns Instrument objects. The overridden field
      returns Brass objects instead. */
      XmlElementAttribute attr = new XmlElementAttribute();
      attr.ElementName = "Brass";
      attr.Type = typeof(Brass);

      // Add the element to the collection of elements.
      attrs.XmlElements.Add(attr);

      // Create the XmlAttributeOverrides object.
      XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();

      /* Add the type of the class that contains the overridden
      member and the XmlAttributes to override it with to the
      XmlAttributeOverrides object. */
      attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);

      // Create the XmlSerializer using the XmlAttributeOverrides.
      XmlSerializer s =
      new XmlSerializer(typeof(Orchestra), attrOverrides);

      // Writing the file requires a TextWriter.
      TextWriter writer = new StreamWriter(filename);

      // Create the object that will be serialized.
      Orchestra band = new Orchestra();

      // Create an object of the derived type.
      Brass i = new Brass();
      i.Name = "Trumpet";
      i.IsValved = true;
      Instrument[] myInstruments = {i};
      band.Instruments = myInstruments;

      // Serialize the object.
      s.Serialize(writer,band);
      writer.Close();
   }

   public void DeserializeObject(string filename)
   {
      XmlAttributeOverrides attrOverrides =
         new XmlAttributeOverrides();
      XmlAttributes attrs = new XmlAttributes();

      // Create an XmlElementAttribute to override the Instrument.
      XmlElementAttribute attr = new XmlElementAttribute();
      attr.ElementName = "Brass";
      attr.Type = typeof(Brass);

      // Add the XmlElementAttribute to the collection of objects.
      attrs.XmlElements.Add(attr);

      attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);

      // Create the XmlSerializer using the XmlAttributeOverrides.
      XmlSerializer s =
      new XmlSerializer(typeof(Orchestra), attrOverrides);

      FileStream fs = new FileStream(filename, FileMode.Open);
      Orchestra band = (Orchestra) s.Deserialize(fs);
      Console.WriteLine("Brass:");

      /* The difference between deserializing the overridden
      XML document and serializing it is this: To read the derived
      object values, you must declare an object of the derived type
      (Brass), and cast the Instrument instance to it. */
      Brass b;
      foreach(Instrument i in band.Instruments)
      {
         b = (Brass)i;
         Console.WriteLine(
         b.Name + "\n" +
         b.IsValved);
      }
   }
}
Option Explicit
Option Strict

Imports System.IO
Imports System.Xml.Serialization

Public Class Orchestra
    Public Instruments() As Instrument
End Class

Public Class Instrument
    Public Name As String
End Class

Public Class Brass
    Inherits Instrument
    Public IsValved As Boolean
End Class

Public Class Run
    
    Public Shared Sub Main()
        Dim test As New Run()
        test.SerializeObject("Override.xml")
        test.DeserializeObject("Override.xml")
    End Sub
        
    Public Sub SerializeObject(ByVal filename As String)
        ' Each overridden field, property, or type requires
        ' an XmlAttributes object. 
        Dim attrs As New XmlAttributes()
        
        ' Create an XmlElementAttribute to override the
        ' field that returns Instrument objects. The overridden field
        ' returns Brass objects instead. 
        Dim attr As New XmlElementAttribute()
        attr.ElementName = "Brass"
        attr.Type = GetType(Brass)
        
        ' Add the element to the collection of elements.
        attrs.XmlElements.Add(attr)
        
        ' Create the XmlAttributeOverrides object.
        Dim attrOverrides As New XmlAttributeOverrides()
        
        ' Add the type of the class that contains the overridden
        ' member and the XmlAttributes to override it with to the
        ' XmlAttributeOverrides object. 
        attrOverrides.Add(GetType(Orchestra), "Instruments", attrs)
        
        ' Create the XmlSerializer using the XmlAttributeOverrides.
        Dim s As New XmlSerializer(GetType(Orchestra), attrOverrides)
        
        ' Writing the file requires a TextWriter.
        Dim writer As New StreamWriter(filename)
        
        ' Create the object that will be serialized.
        Dim band As New Orchestra()
        
        ' Create an object of the derived type.
        Dim i As New Brass()
        i.Name = "Trumpet"
        i.IsValved = True
        Dim myInstruments() As Instrument = {i}
        band.Instruments = myInstruments
        
        ' Serialize the object.
        s.Serialize(writer, band)
        writer.Close()
    End Sub    
    
    Public Sub DeserializeObject(filename As String)
        Dim attrOverrides As New XmlAttributeOverrides()
        Dim attrs As New XmlAttributes()
        
        ' Create an XmlElementAttribute to override the Instrument.
        Dim attr As New XmlElementAttribute()
        attr.ElementName = "Brass"
        attr.Type = GetType(Brass)
        
        ' Add the XmlElementAttribute to the collection of objects.
        attrs.XmlElements.Add(attr)
        
        attrOverrides.Add(GetType(Orchestra), "Instruments", attrs)
        
        ' Create the XmlSerializer using the XmlAttributeOverrides.
        Dim s As New XmlSerializer(GetType(Orchestra), attrOverrides)
        
        Dim fs As New FileStream(filename, FileMode.Open)
        Dim band As Orchestra = CType(s.Deserialize(fs), Orchestra)
        Console.WriteLine("Brass:")
        
        ' The difference between deserializing the overridden
        ' XML document and serializing it is this: To read the derived
        ' object values, you must declare an object of the derived type
        ' (Brass), and cast the Instrument instance to it. 
        Dim b As Brass
        Dim i As Instrument
        For Each i In  band.Instruments
            b = CType(i, Brass)
            Console.WriteLine(b.Name & ControlChars.Cr & b.IsValved)
        Next i
    End Sub
End Class

설명

이렇게 XmlAttributeOverrides 하면 XmlSerializer 개체 집합을 직렬화하는 기본 방법을 재정의할 수 있습니다. 이러한 방식으로 serialization을 재정의하는 데는 두 가지 용도가 있습니다. 먼저 원본에 액세스할 수 없는 경우에도 DLL에 있는 개체의 serialization을 제어하고 보강할 수 있습니다. 둘째, 직렬화 가능한 클래스 집합을 하나 만들 수 있지만 여러 가지 방법으로 개체를 직렬화할 수 있습니다. 예를 들어, XML 요소로 클래스 인스턴스 멤버를 직렬화 하는 작업을 하는 대신 serialize 할 수 있습니다 이러한 XML 특성으로 전송 보다 효율적인 문서의 결과입니다.

개체를 XmlAttributeOverrides 만든 후 생성자에 인수 XmlSerializer 로 전달합니다. 결과 XmlSerializer 포함 된 데이터를 사용 하는 XmlAttributeOverrides 개체 직렬화 되는 방식을 제어 하는 특성을 재정의할 수 있습니다. 이를 XmlAttributeOverrides 위해 재정의되는 개체 형식의 컬렉션과 XmlAttributes 재정의된 각 개체 형식과 연결된 개체가 포함됩니다. 개체 자체에는 XmlAttributes 각 필드, 속성 또는 클래스가 serialize되는 방법을 제어하는 적절한 특성 개체 집합이 포함되어 있습니다.

개체를 만들고 사용하는 XmlAttributeOverrides 프로세스는 다음과 같습니다.

  1. XmlAttributes 개체 만들기

  2. 재정의 되는 개체에 적절 한 특성 개체를 만듭니다. For example, to override a field or property, create an XmlElementAttribute, using the new, derived type. 필요에 따라 새 ElementName클래스를 할당하거나 Namespace 기본 클래스의 특성 이름 또는 네임스페이스를 재정의할 수 있습니다.

  3. 적절 한 특성 개체를 추가 XmlAttributes 속성 또는 컬렉션입니다. 예를 들어 재정의되는 멤버 이름을 지정하여 개체 컬렉션 XmlAttributes 에 추가 XmlElementAttribute XmlElements 합니다.

  4. XmlAttributeOverrides 개체 만들기

  5. 메서드를 Add 사용하여 개체를 XmlAttributes 개체에 XmlAttributeOverrides 추가합니다. 재정의되는 개체가 XmlRootAttribute 또는 XmlTypeAttribute재정의된 개체인 경우 재정의된 개체의 형식만 지정하면 됩니다. 하지만 필드 또는 속성을 재정의 하는 경우 재정의 된 멤버의 이름을 지정 해야 합니다.

  6. 생성할 때를 XmlSerializer, 전달 합니다 XmlAttributeOverridesXmlSerializer 생성자.

  7. 결과를 XmlSerializer 사용하여 파생 클래스 개체를 직렬화하거나 역직렬화합니다.

생성자

XmlAttributeOverrides()

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

속성

Item[Type, String]

지정한 (기본 클래스) 형식과 관련된 개체를 가져옵니다. 해당 멤버 매개 변수는 재정의되는 기본 클래스 멤버를 지정합니다.

Item[Type]

지정한 기본 클래스 형식과 관련된 개체를 가져옵니다.

메서드

Add(Type, String, XmlAttributes)

XmlAttributes 개체를 XmlAttributes 개체 컬렉션에 추가합니다. type 매개 변수는 재정의할 개체를 지정합니다. member 매개 변수는 재정의되는 멤버의 이름을 지정합니다.

Add(Type, XmlAttributes)

XmlAttributes 개체를 XmlAttributes 개체 컬렉션에 추가합니다. type 매개 변수는 XmlAttributes 개체로 재정의할 개체를 지정합니다.

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)

적용 대상

추가 정보