XmlAttributeOverrides Class

Definition

XmlSerializer를 사용하여 개체를 직렬화하거나 역직렬화하면 속성, 필드 및 클래스 특성을 재정의할 수 있습니다.Allows you to override property, field, and class attributes when you use the XmlSerializer to serialize or deserialize an object.

public ref class XmlAttributeOverrides
public class XmlAttributeOverrides
type XmlAttributeOverrides = class
Public Class XmlAttributeOverrides
Inheritance
XmlAttributeOverrides

Examples

다음 예제에서는 Instrument 개체의 배열을 반환 하는 Instruments 라는 단일 필드를 포함 하는 Orchestra라는 클래스를 serialize 합니다.The following example serializes a class named Orchestra, which contains a single field named Instruments that returns an array of Instrument objects. 두 번째 클래스가 Brass 에서 상속 되는 Instrument 클래스입니다.A second class named Brass inherits from the Instrument class. 이 예제에서는 XmlAttributeOverrides 클래스의 인스턴스를 사용 하 여 Instrument 필드를 재정의 합니다 .이 필드에는 Brass 개체를 사용할 수 있습니다.The example uses an instance of the XmlAttributeOverrides class to override the Instrument field, allowing the field to accept Brass objects.

#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

Remarks

XmlAttributeOverrides를 사용 하면 XmlSerializer에서 개체 집합을 serialize 하는 기본 방법을 재정의할 수 있습니다.The XmlAttributeOverrides enables the XmlSerializer to override the default way of serializing a set of objects. 용도 이러한 방식으로 serialization을 재정의 합니다: 제어 하 고는 DLL에 있는 개체의 serialization을 보강할 수 먼저 원본;에 액세스할 수 없는 경우에 둘째, serializable 클래스의 집합을 만들 수 있지만 여러 가지 방법으로 개체를 직렬화 할.Overriding serialization in this way has two uses: first, you can control and augment the serialization of objects found in a DLL--even if you do not have access to the source; second, you can create one set of serializable classes, but serialize the objects in multiple ways. 예를 들어, XML 요소로 클래스 인스턴스 멤버를 직렬화 하는 작업을 하는 대신 serialize 할 수 있습니다 이러한 XML 특성으로 전송 보다 효율적인 문서의 결과입니다.For example, instead of serializing members of a class instance as XML elements, you can serialize them as XML attributes, resulting in a more efficient document to transport.

XmlAttributeOverrides 개체를 만든 후에 XmlSerializer 생성자에 인수로 전달 합니다.After you create an XmlAttributeOverrides object, you pass it as an argument to the XmlSerializer constructor. 결과 XmlSerializer 포함 된 데이터를 사용 하는 XmlAttributeOverrides 개체 직렬화 되는 방식을 제어 하는 특성을 재정의할 수 있습니다.The resulting XmlSerializer uses the data contained by the XmlAttributeOverrides to override attributes that control how objects are serialized. 이를 위해 XmlAttributeOverrides는 재정의 되는 개체 유형 및 재정의 된 각 개체 유형과 연결 된 XmlAttributes 개체의 컬렉션을 포함 합니다.To accomplish this, the XmlAttributeOverrides contains a collection of the object types that are overridden, as well as an XmlAttributes object associated with each overridden object type. XmlAttributes 개체 자체는 각 필드, 속성 또는 클래스를 serialize 하는 방법을 제어 하는 적절 한 특성 개체 집합을 포함 합니다.The XmlAttributes object itself contains an appropriate set of attribute objects that control how each field, property, or class is serialized.

XmlAttributeOverrides 개체를 만들고 사용 하는 프로세스는 다음과 같습니다.The process for creating and using an XmlAttributeOverrides object is as follows:

  1. XmlAttributes 개체를 만듭니다.Create an XmlAttributes object.

  2. 재정의 되는 개체에 적절 한 특성 개체를 만듭니다.Create an attribute object that is appropriate to the object being overridden. 예를 들어, 필드 또는 속성을 재정의 하려면 새로운 파생 형식을 사용 하 여 XmlElementAttribute를 만듭니다.For example, to override a field or property, create an XmlElementAttribute, using the new, derived type. 필요에 따라 기본 클래스의 특성 이름 또는 네임 스페이스를 재정의 하는 새 ElementName또는 Namespace를 할당할 수 있습니다.You can optionally assign a new ElementName, or Namespace that overrides the base class's attribute name or namespace.

  3. 적절 한 특성 개체를 추가 XmlAttributes 속성 또는 컬렉션입니다.Add the attribute object to the appropriate XmlAttributes property or collection. 예를 들어 XmlElementAttributeXmlAttributes 개체의 XmlElements 컬렉션에 추가 하 고 재정의 되는 멤버 이름을 지정 합니다.For example, you would add the XmlElementAttribute to the XmlElements collection of the XmlAttributes object, specifying the member name that is being overridden.

  4. XmlAttributeOverrides 개체를 만듭니다.Create an XmlAttributeOverrides object.

  5. Add 메서드를 사용 하 여 XmlAttributes 개체를 XmlAttributeOverrides 개체에 추가 합니다.Using the Add method, add the XmlAttributes object to the XmlAttributeOverrides object. 재정의 되는 개체가 XmlRootAttribute 또는 XmlTypeAttribute이면 재정의 된 개체의 형식만 지정 하면 됩니다.If the object being overridden is an XmlRootAttribute or XmlTypeAttribute, you need only to specify the type of the overridden object. 하지만 필드 또는 속성을 재정의 하는 경우 재정의 된 멤버의 이름을 지정 해야 합니다.But if you are overriding a field or property, you must also specify the name of the overridden member.

  6. 생성할 때를 XmlSerializer, 전달 합니다 XmlAttributeOverridesXmlSerializer 생성자.When constructing the XmlSerializer, pass the XmlAttributeOverrides to the XmlSerializer constructor.

  7. 결과 XmlSerializer를 사용 하 여 파생 클래스 개체를 serialize 하거나 deserialize 합니다.Use the resulting XmlSerializer to serialize or deserialize the derived class objects.

Constructors

XmlAttributeOverrides() XmlAttributeOverrides 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the XmlAttributeOverrides class.

Properties

Item[Type, String]

지정 된 (기본 클래스) 형식과 연결 된 개체를 가져옵니다.Gets the object associated with the specified (base-class) type. 해당 멤버 매개 변수 재정의 되는 기본 클래스 멤버를 지정 합니다.The member parameter specifies the base-class member that is overridden.

Item[Type]

지정 된, 기본 클래스 형식과 연결 된 개체를 가져옵니다.Gets the object associated with the specified, base-class, type.

Methods

Add(Type, String, XmlAttributes)

XmlAttributes 개체를 XmlAttributes 개체 컬렉션에 추가합니다.Adds an XmlAttributes object to the collection of XmlAttributes objects. type 매개 변수는 재정의할 개체를 지정합니다.The type parameter specifies an object to be overridden. member 매개 변수는 재정의되는 멤버의 이름을 지정합니다.The member parameter specifies the name of a member that is overridden.

Add(Type, XmlAttributes)

XmlAttributes 개체를 XmlAttributes 개체 컬렉션에 추가합니다.Adds an XmlAttributes object to the collection of XmlAttributes objects. type 매개 변수는 XmlAttributes 개체로 재정의할 개체를 지정합니다.The type parameter specifies an object to be overridden by the XmlAttributes object.

Equals(Object)

지정한 개체와 현재 개체가 같은지 여부를 확인합니다.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode()

기본 해시 함수로 작동합니다.Serves as the default hash function.

(Inherited from Object)
GetType()

현재 인스턴스의 Type을 가져옵니다.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString()

현재 개체를 나타내는 문자열을 반환합니다.Returns a string that represents the current object.

(Inherited from Object)

Applies to

See also