XmlSerializer 생성자

정의

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

오버로드

XmlSerializer()

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

XmlSerializer(Type)

지정된 형식의 개체를 XML 문서로 직렬화하고 XML 문서를 지정된 형식의 개체로 역직렬화할 수 있는 XmlSerializer 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into objects of the specified type.

XmlSerializer(XmlTypeMapping)

특정 형식을 다른 형식에 매핑하는 개체를 사용하여 XmlSerializer 클래스의 인스턴스를 초기화합니다.Initializes an instance of the XmlSerializer class using an object that maps one type to another.

XmlSerializer(Type, String)

지정된 형식의 개체를 XML 문서로 직렬화하고 XML 문서를 지정된 형식의 개체로 역직렬화할 수 있는 XmlSerializer 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into objects of the specified type. 모든 XML 요소에 대 한 기본 네임 스페이스를 지정합니다.Specifies the default namespace for all the XML elements.

XmlSerializer(Type, Type[])

지정된 형식의 개체를 XML 문서로 직렬화하고 XML 문서를 지정된 형식의 개체로 역직렬화할 수 있는 XmlSerializer 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into object of a specified type. 필드 또는 속성이 배열을 반환하는 경우 extraTypes 매개 변수는 배열에 삽입될 수 있는 개체를 지정합니다.If a property or field returns an array, the extraTypes parameter specifies objects that can be inserted into the array.

XmlSerializer(Type, XmlAttributeOverrides)

지정된 형식의 개체를 XML 문서로 직렬화하고 XML 문서를 지정된 형식의 개체로 역직렬화할 수 있는 XmlSerializer 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into objects of the specified type. Serialize 될 각 개체를 포함할 수 있으며이 오버 로드는 다른 클래스를 사용 하 여 재정의할 수 있는 클래스의 인스턴스.Each object to be serialized can itself contain instances of classes, which this overload can override with other classes.

XmlSerializer(Type, XmlRootAttribute)

지정된 형식의 개체를 XML 문서로 직렬화하고 XML 문서를 지정된 형식의 개체로 역직렬화할 수 있는 XmlSerializer 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize an XML document into object of the specified type. 또한 XML 루트 요소로 사용할 클래스를 지정 합니다.It also specifies the class to use as the XML root element.

XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String)

XmlSerializer 형식의 개체를 XML 문서 인스턴스로 직렬화하고 XML 문서 인스턴스를 Object 형식의 개체로 역직렬화할 수 있는 Object 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the XmlSerializer class that can serialize objects of type Object into XML document instances, and deserialize XML document instances into objects of type Object. Serialize 될 각 개체를 포함할 수 있으며이 오버 로드를 다른 클래스로 재정의 하는 클래스의 인스턴스.Each object to be serialized can itself contain instances of classes, which this overload overrides with other classes. 또한이 오버 로드는 모든 XML 요소 및 XML 루트 요소로 사용 하는 클래스에 대 한 기본 네임 스페이스를 지정 합니다.This overload also specifies the default namespace for all the XML elements and the class to use as the XML root element.

XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String)

XmlSerializer 형식의 개체를 XML 문서 인스턴스로 직렬화하고 XML 문서 인스턴스를 Object 형식의 개체로 역직렬화할 수 있는 Object 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the XmlSerializer class that can serialize objects of type Object into XML document instances, and deserialize XML document instances into objects of type Object. Serialize 될 각 개체를 포함할 수 있으며이 오버 로드를 다른 클래스로 재정의 하는 클래스의 인스턴스.Each object to be serialized can itself contain instances of classes, which this overload overrides with other classes. 또한이 오버 로드는 모든 XML 요소 및 XML 루트 요소로 사용 하는 클래스에 대 한 기본 네임 스페이스를 지정 합니다.This overload also specifies the default namespace for all the XML elements and the class to use as the XML root element.

XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String, Evidence)

지정된 형식의 개체를 XML 문서 인스턴스로 직렬화하고 XML 문서 인스턴스를 지정된 형식의 개체로 역직렬화할 수 있는 XmlSerializer 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML document instances, and deserialize XML document instances into objects of the specified type. 이 오버 로드를 사용 하면 기본 네임 스페이스를 모든 XML 요소에 대 한 XML 루트 요소, 위치 및 액세스에 필요한 자격 증명으로 사용 하는 클래스 뿐만 아니라 작업을 serialization 또는 deserialization 중에 발생할 수 있는 다른 유형과 제공할 수 있습니다. .This overload allows you to supply other types that can be encountered during a serialization or deserialization operation, as well as a default namespace for all XML elements, the class to use as the XML root element, its location, and credentials required for access.

XmlSerializer()

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

protected:
 XmlSerializer();
protected XmlSerializer ();
Protected Sub New ()

XmlSerializer(Type)

지정된 형식의 개체를 XML 문서로 직렬화하고 XML 문서를 지정된 형식의 개체로 역직렬화할 수 있는 XmlSerializer 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into objects of the specified type.

public:
 XmlSerializer(Type ^ type);
public XmlSerializer (Type type);
new System.Xml.Serialization.XmlSerializer : Type -> System.Xml.Serialization.XmlSerializer
Public Sub New (type As Type)

매개 변수

type
Type

XmlSerializer가 serialize할 수 있는 개체의 형식입니다.The type of the object that this XmlSerializer can serialize.

예제

다음 예제에서는 Widget이라는 개체를 serialize 하는 XmlSerializer를 생성 합니다.The following example constructs an XmlSerializer that serializes an object named Widget. 이 예제에서는 Serialize 메서드를 호출 하기 전에 개체의 다양 한 속성을 설정 합니다.The example sets various properties of the object before calling the Serialize method.

private:
   void SerializeObject( String^ filename )
   {
      XmlSerializer^ serializer =
         gcnew XmlSerializer( OrderedItem::typeid );

      // Create an instance of the class to be serialized.
      OrderedItem^ i = gcnew OrderedItem;

      // Set the public property values.
      i->ItemName = "Widget";
      i->Description = "Regular Widget";
      i->Quantity = 10;
      i->UnitPrice = (Decimal)2.30;

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

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

public:
   // This is the class that will be serialized.
   ref class OrderedItem
   {
   public:
      String^ ItemName;
      String^ Description;
      Decimal UnitPrice;
      int Quantity;
   };
private void SerializeObject(string filename)
{
   XmlSerializer serializer = 
   new XmlSerializer(typeof(OrderedItem));

   // Create an instance of the class to be serialized.
   OrderedItem i = new OrderedItem();

   // Set the public property values.
   i.ItemName = "Widget";
   i.Description = "Regular Widget";
   i.Quantity = 10;
   i.UnitPrice = (decimal) 2.30;

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

   // Serialize the object, and close the TextWriter.
   serializer.Serialize(writer, i);
   writer.Close();
}

// This is the class that will be serialized.
public class OrderedItem
{
   public string ItemName;
   public string Description;
   public decimal UnitPrice;
   public int Quantity;
}

Private Sub SerializeObject(ByVal filename As String)
    Dim serializer As New XmlSerializer(GetType(OrderedItem))
    
    ' Create an instance of the class to be serialized.
    Dim i As New OrderedItem()
    
    ' Set the public property values.
    With i
        .ItemName = "Widget"
        .Description = "Regular Widget"
        .Quantity = 10
        .UnitPrice = CDec(2.3)
    End With
    
    ' Writing the document requires a TextWriter.
    Dim writer As New StreamWriter(filename)
    
    ' Serialize the object, and close the TextWriter.
    serializer.Serialize(writer, i)
    writer.Close()
End Sub


' This is the class that will be serialized.
Public Class OrderedItem
    Public ItemName As String
    Public Description As String
    Public UnitPrice As Decimal
    Public Quantity As Integer
End Class

설명

일반적으로 애플리케이션 정의 여러 클래스를 XmlSerializer 단일 XML 인스턴스 문서를 변환 합니다.Commonly, an application defines several classes that the XmlSerializer converts into a single XML-instance document. 그러나 XmlSerializer는 XML 루트 요소를 나타내는 클래스의 형식인 하나의 형식만 알고 있어야 합니다.However, the XmlSerializer must know only one type--the type of the class that represents the XML root element. XmlSerializer는 모든 하위 클래스 인스턴스를 자동으로 직렬화 합니다.The XmlSerializer automatically serializes all subordinate class instances. 마찬가지로, XML 루트 요소의 유형만 deserialization에 필요 합니다.Similarly, only the type of the XML root element is required for deserialization.

추가 정보

XmlSerializer(XmlTypeMapping)

특정 형식을 다른 형식에 매핑하는 개체를 사용하여 XmlSerializer 클래스의 인스턴스를 초기화합니다.Initializes an instance of the XmlSerializer class using an object that maps one type to another.

public:
 XmlSerializer(System::Xml::Serialization::XmlTypeMapping ^ xmlTypeMapping);
public XmlSerializer (System.Xml.Serialization.XmlTypeMapping xmlTypeMapping);
new System.Xml.Serialization.XmlSerializer : System.Xml.Serialization.XmlTypeMapping -> System.Xml.Serialization.XmlSerializer
Public Sub New (xmlTypeMapping As XmlTypeMapping)

매개 변수

xmlTypeMapping
XmlTypeMapping

특정 형식을 다른 형식에 매핑하는 XmlTypeMapping입니다.An XmlTypeMapping that maps one type to another.

예제

다음 예제에서는 라는 클래스를 직렬화 Group합니다.The following example serializes a class named Group. GroupName, IgnoreThis 필드 및 GroupType 열거형의 멤버에 대 한 serialization이 재정의 됩니다.The serialization of the GroupName, IgnoreThis fields, and the members of the GroupType enumeration are overridden. CreateOverrideSerializer 메서드에서 SoapAttributeOverrides 개체가 만들어지고, 재정의 된 각 멤버나 열거형에 대해 적절 한 속성 집합을 사용 하 여 SoapAttributes 개체가 만들어지고 SoapAttributeOverrides 개체에 추가 됩니다.In the CreateOverrideSerializer method, a SoapAttributeOverrides object is created, and for each overridden member or enumeration, a SoapAttributes object is created with the appropriate property set and added to the SoapAttributeOverrides object. XmlMapping 개체는 SoapAttributeOverrides 개체를 사용 하 여 만들며,이 XmlMapping 개체는 기본 serialization을 재정의 하는 XmlSerializer를 만드는 데 사용 됩니다.An XmlMapping object is created using the SoapAttributeOverrides object, and that XmlMapping object is used to create the XmlSerializer that overrides the default serialization.

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

using namespace System;
using namespace System::IO;
using namespace System::Text;
using namespace System::Xml;
using namespace System::Xml::Serialization;
using namespace System::Xml::Schema;
ref class Car;

// SoapInclude allows Vehicle to accept Car type.

[SoapInclude(Car::typeid)]
public ref class Vehicle abstract
{
public:
   String^ licenseNumber;
   DateTime makeDate;
};

public ref class Car: public Vehicle{};

public enum class GroupType
{
   // These enums can be overridden.
   [SoapEnum("Small")]
   A,
   [SoapEnum("Large")]
   B
};

public ref class Group
{
public:

   [SoapAttributeAttribute(Namespace="http://www.cpandl.com")]
   String^ GroupName;

   [SoapAttributeAttribute(DataType="base64Binary")]
   array<Byte>^GroupNumber;

   [SoapAttributeAttribute(DataType="date",AttributeName="CreationDate")]
   DateTime Today;

   [SoapElement(DataType="nonNegativeInteger",ElementName="PosInt")]
   String^ PostitiveInt;

   // This is ignored when serialized unless it's overridden.

   [SoapIgnore]
   bool IgnoreThis;
   GroupType Grouptype;
   Vehicle^ MyVehicle;

   // The SoapInclude allows the method to return a Car.

   [SoapInclude(Car::typeid)]
   Vehicle^ myCar( String^ licNumber )
   {
      Vehicle^ v;
      if ( licNumber->Equals( "" ) )
      {
         v = gcnew Car;
         v->licenseNumber = "!!!!!!";
      }
      else
      {
         v = gcnew Car;
         v->licenseNumber = licNumber;
      }

      return v;
   }
};

public ref class Run
{
public:
   static void main()
   {
      Run^ test = gcnew Run;
      test->SerializeOriginal( "SoapOriginal.xml" );
      test->SerializeOverride( "SoapOverrides.xml" );
      test->DeserializeOriginal( "SoapOriginal.xml" );
      test->DeserializeOverride( "SoapOverrides.xml" );
   }

   void SerializeOriginal( String^ filename )
   {
      // Create an instance of the XmlSerializer class.
      XmlTypeMapping^ myMapping = (gcnew SoapReflectionImporter)->ImportTypeMapping( Group::typeid );
      XmlSerializer^ mySerializer = gcnew XmlSerializer( myMapping );
      Group^ myGroup = MakeGroup();

      // Writing the file requires a TextWriter.
      XmlTextWriter^ writer = gcnew XmlTextWriter( filename,Encoding::UTF8 );
      writer->Formatting = Formatting::Indented;
      writer->WriteStartElement( "wrapper" );

      // Serialize the class, and close the TextWriter.
      mySerializer->Serialize( writer, myGroup );
      writer->WriteEndElement();
      writer->Close();
   }

   void SerializeOverride( String^ filename )
   {
      // Create an instance of the XmlSerializer class
      // that overrides the serialization.
      XmlSerializer^ overRideSerializer = CreateOverrideSerializer();
      Group^ myGroup = MakeGroup();

      // Writing the file requires a TextWriter.
      XmlTextWriter^ writer = gcnew XmlTextWriter( filename,Encoding::UTF8 );
      writer->Formatting = Formatting::Indented;
      writer->WriteStartElement( "wrapper" );

      // Serialize the class, and close the TextWriter.
      overRideSerializer->Serialize( writer, myGroup );
      writer->WriteEndElement();
      writer->Close();
   }

private:
   Group^ MakeGroup()
   {
      // Create an instance of the class that will be serialized.
      Group^ myGroup = gcnew Group;

      // Set the object properties.
      myGroup->GroupName = ".NET";
      array<Byte>^hexByte = {Convert::ToByte( 100 ),Convert::ToByte( 50 )};
      myGroup->GroupNumber = hexByte;
      DateTime myDate = DateTime(2002,5,2);
      myGroup->Today = myDate;
      myGroup->PostitiveInt = "10000";
      myGroup->IgnoreThis = true;
      myGroup->Grouptype = GroupType::B;
      Car^ thisCar = dynamic_cast<Car^>(myGroup->myCar( "1234566" ));
      myGroup->MyVehicle = thisCar;
      return myGroup;
   }

public:
   void DeserializeOriginal( String^ filename )
   {
      // Create an instance of the XmlSerializer class.
      XmlTypeMapping^ myMapping = (gcnew SoapReflectionImporter)->ImportTypeMapping( Group::typeid );
      XmlSerializer^ mySerializer = gcnew XmlSerializer( myMapping );

      // Reading the file requires an  XmlTextReader.
      XmlTextReader^ reader = gcnew XmlTextReader( filename );
      reader->ReadStartElement( "wrapper" );

      // Deserialize and cast the object.
      Group^ myGroup;
      myGroup = dynamic_cast<Group^>(mySerializer->Deserialize( reader ));
      reader->ReadEndElement();
      reader->Close();
   }

   void DeserializeOverride( String^ filename )
   {
      // Create an instance of the XmlSerializer class.
      XmlSerializer^ overRideSerializer = CreateOverrideSerializer();

      // Reading the file requires an XmlTextReader.
      XmlTextReader^ reader = gcnew XmlTextReader( filename );
      reader->ReadStartElement( "wrapper" );

      // Deserialize and cast the object.
      Group^ myGroup;
      myGroup = dynamic_cast<Group^>(overRideSerializer->Deserialize( reader ));
      reader->ReadEndElement();
      reader->Close();
      ReadGroup( myGroup );
   }

private:
   void ReadGroup( Group^ myGroup )
   {
      Console::WriteLine( myGroup->GroupName );
      Console::WriteLine( myGroup->GroupNumber[ 0 ] );
      Console::WriteLine( myGroup->GroupNumber[ 1 ] );
      Console::WriteLine( myGroup->Today );
      Console::WriteLine( myGroup->PostitiveInt );
      Console::WriteLine( myGroup->IgnoreThis );
      Console::WriteLine();
   }

   XmlSerializer^ CreateOverrideSerializer()
   {
      SoapAttributeOverrides^ mySoapAttributeOverrides = gcnew SoapAttributeOverrides;
      SoapAttributes^ soapAtts = gcnew SoapAttributes;
      SoapElementAttribute^ mySoapElement = gcnew SoapElementAttribute;
      mySoapElement->ElementName = "xxxx";
      soapAtts->SoapElement = mySoapElement;
      mySoapAttributeOverrides->Add( Group::typeid, "PostitiveInt", soapAtts );

      // Override the IgnoreThis property.
      SoapIgnoreAttribute^ myIgnore = gcnew SoapIgnoreAttribute;
      soapAtts = gcnew SoapAttributes;
      soapAtts->SoapIgnore = false;
      mySoapAttributeOverrides->Add( Group::typeid, "IgnoreThis", soapAtts );

      // Override the GroupType enumeration. 
      soapAtts = gcnew SoapAttributes;
      SoapEnumAttribute^ xSoapEnum = gcnew SoapEnumAttribute;
      xSoapEnum->Name = "Over1000";
      soapAtts->GroupType::SoapEnum = xSoapEnum;

      // Add the SoapAttributes to the 
      // mySoapAttributeOverridesrides object.
      mySoapAttributeOverrides->Add( GroupType::typeid, "A", soapAtts );

      // Create second enumeration and add it.
      soapAtts = gcnew SoapAttributes;
      xSoapEnum = gcnew SoapEnumAttribute;
      xSoapEnum->Name = "ZeroTo1000";
      soapAtts->GroupType::SoapEnum = xSoapEnum;
      mySoapAttributeOverrides->Add( GroupType::typeid, "B", soapAtts );

      // Override the Group type.
      soapAtts = gcnew SoapAttributes;
      SoapTypeAttribute^ soapType = gcnew SoapTypeAttribute;
      soapType->TypeName = "Team";
      soapAtts->SoapType = soapType;
      mySoapAttributeOverrides->Add( Group::typeid, soapAtts );

      // Create an XmlTypeMapping that is used to create an instance 
      // of the XmlSerializer. Then return the XmlSerializer object.
      XmlTypeMapping^ myMapping = (gcnew SoapReflectionImporter( mySoapAttributeOverrides ))->ImportTypeMapping( Group::typeid );
      XmlSerializer^ ser = gcnew XmlSerializer( myMapping );
      return ser;
   }
};

int main()
{
   Run::main();
}
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Schema;

public class Group
{
   [SoapAttribute (Namespace = "http://www.cpandl.com")]
   public string GroupName;
   
   [SoapAttribute(DataType = "base64Binary")]
   public Byte [] GroupNumber;

   [SoapAttribute(DataType = "date", AttributeName = "CreationDate")]
   public DateTime Today;
   [SoapElement(DataType = "nonNegativeInteger", ElementName = "PosInt")]
   public string PostitiveInt;
   // This is ignored when serialized unless it's overridden.
   [SoapIgnore] 
   public bool IgnoreThis;
   
   public GroupType Grouptype;

   public Vehicle MyVehicle;

   // The SoapInclude allows the method to return a Car.
   [SoapInclude(typeof(Car))]
   public Vehicle myCar(string licNumber)
   {
      Vehicle v;
      if(licNumber == "")
         {
            v = new Car();
        v.licenseNumber = "!!!!!!";
     }
      else
     {
       v = new Car();
       v.licenseNumber = licNumber;
     }
      return v;
   }
}
  
// SoapInclude allows Vehicle to accept Car type.
[SoapInclude(typeof(Car))]
public abstract class Vehicle
{
   public string licenseNumber;
   public DateTime makeDate;
}

public class Car: Vehicle
{
}

public enum GroupType
{
   // These enums can be overridden.
   [SoapEnum("Small")]
   A,
   [SoapEnum("Large")]
   B
}
 
public class Run
{
   public static void Main()
   {
      Run test = new Run();
      test.SerializeOriginal("SoapOriginal.xml");
      test.SerializeOverride("SoapOverrides.xml");
      test.DeserializeOriginal("SoapOriginal.xml");
      test.DeserializeOverride("SoapOverrides.xml");
   }
   public void SerializeOriginal(string filename)
   {
      // Create an instance of the XmlSerializer class.
      XmlTypeMapping myMapping = 
      (new SoapReflectionImporter().ImportTypeMapping(
      typeof(Group)));
      XmlSerializer mySerializer =  
      new XmlSerializer(myMapping);
      Group myGroup=MakeGroup();
      // Writing the file requires a TextWriter.
      XmlTextWriter writer = 
      new XmlTextWriter(filename, Encoding.UTF8);
      writer.Formatting = Formatting.Indented;
      writer.WriteStartElement("wrapper");
      // Serialize the class, and close the TextWriter.
      mySerializer.Serialize(writer, myGroup);
      writer.WriteEndElement();
      writer.Close();
   }

   public void SerializeOverride(string filename)
   {
      // Create an instance of the XmlSerializer class
      // that overrides the serialization.
      XmlSerializer overRideSerializer = CreateOverrideSerializer();
      Group myGroup=MakeGroup();
      // Writing the file requires a TextWriter.
      XmlTextWriter writer = 
      new XmlTextWriter(filename, Encoding.UTF8);
      writer.Formatting = Formatting.Indented;
      writer.WriteStartElement("wrapper");
      // Serialize the class, and close the TextWriter.
      overRideSerializer.Serialize(writer, myGroup);
      writer.WriteEndElement();
      writer.Close();
   }

   private Group MakeGroup(){
      // Create an instance of the class that will be serialized.
      Group myGroup = new Group();

      // Set the object properties.
      myGroup.GroupName = ".NET";

      Byte [] hexByte = new Byte[2]{Convert.ToByte(100),
      Convert.ToByte(50)};
      myGroup.GroupNumber = hexByte;

      DateTime myDate = new DateTime(2002,5,2);
      myGroup.Today = myDate;
      myGroup.PostitiveInt= "10000";
      myGroup.IgnoreThis=true;
      myGroup.Grouptype= GroupType.B;
      Car thisCar =(Car)  myGroup.myCar("1234566");
      myGroup.MyVehicle=thisCar;
      return myGroup;
   }   	

   public void DeserializeOriginal(string filename)
   {
      // Create an instance of the XmlSerializer class.
      XmlTypeMapping myMapping = 
      (new SoapReflectionImporter().ImportTypeMapping(
      typeof(Group)));
      XmlSerializer mySerializer =  
      new XmlSerializer(myMapping);

      // Reading the file requires an  XmlTextReader.
      XmlTextReader reader= 
      new XmlTextReader(filename);
      reader.ReadStartElement("wrapper");

      // Deserialize and cast the object.
      Group myGroup; 
      myGroup = (Group) mySerializer.Deserialize(reader);
      reader.ReadEndElement();
      reader.Close();
   }

   public void DeserializeOverride(string filename)
   {
      // Create an instance of the XmlSerializer class.
      XmlSerializer overRideSerializer = CreateOverrideSerializer();

      // Reading the file requires an  XmlTextReader.
      XmlTextReader reader= 
      new XmlTextReader(filename);
      reader.ReadStartElement("wrapper");

      // Deserialize and cast the object.
      Group myGroup; 
      myGroup = (Group) overRideSerializer.Deserialize(reader);
      reader.ReadEndElement();
      reader.Close();
      ReadGroup(myGroup);
   }

   private void ReadGroup(Group myGroup){
      Console.WriteLine(myGroup.GroupName);
      Console.WriteLine(myGroup.GroupNumber[0]);
      Console.WriteLine(myGroup.GroupNumber[1]);
      Console.WriteLine(myGroup.Today);
      Console.WriteLine(myGroup.PostitiveInt);
      Console.WriteLine(myGroup.IgnoreThis);
      Console.WriteLine();
   }
   private XmlSerializer CreateOverrideSerializer()
   {
      SoapAttributeOverrides mySoapAttributeOverrides = 
      new SoapAttributeOverrides();
      SoapAttributes soapAtts = new SoapAttributes();

      SoapElementAttribute mySoapElement = new SoapElementAttribute();
      mySoapElement.ElementName = "xxxx";
      soapAtts.SoapElement = mySoapElement;
      mySoapAttributeOverrides.Add(typeof(Group), "PostitiveInt", 
      soapAtts);

      // Override the IgnoreThis property.
      SoapIgnoreAttribute myIgnore = new SoapIgnoreAttribute();
      soapAtts = new SoapAttributes();
      soapAtts.SoapIgnore = false;      
      mySoapAttributeOverrides.Add(typeof(Group), "IgnoreThis", 
      soapAtts);

      // Override the GroupType enumeration.	
      soapAtts = new SoapAttributes();
      SoapEnumAttribute xSoapEnum = new SoapEnumAttribute();
      xSoapEnum.Name = "Over1000";
      soapAtts.SoapEnum = xSoapEnum;

      // Add the SoapAttributes to the 
      // mySoapAttributeOverridesrides object.
      mySoapAttributeOverrides.Add(typeof(GroupType), "A", 
      soapAtts);

      // Create second enumeration and add it.
      soapAtts = new SoapAttributes();
      xSoapEnum = new SoapEnumAttribute();
      xSoapEnum.Name = "ZeroTo1000";
      soapAtts.SoapEnum = xSoapEnum;
      mySoapAttributeOverrides.Add(typeof(GroupType), "B", 
      soapAtts);

      // Override the Group type.
      soapAtts = new SoapAttributes();
      SoapTypeAttribute soapType = new SoapTypeAttribute();
      soapType.TypeName = "Team";
      soapAtts.SoapType = soapType;
      mySoapAttributeOverrides.Add(typeof(Group),soapAtts);

      // Create an XmlTypeMapping that is used to create an instance 
      // of the XmlSerializer. Then return the XmlSerializer object.
      XmlTypeMapping myMapping = (new SoapReflectionImporter(
      mySoapAttributeOverrides)).ImportTypeMapping(typeof(Group));
    
      XmlSerializer ser = new XmlSerializer(myMapping);
      return ser;
   }
}
Imports System.IO
Imports System.Text
Imports System.Xml
Imports System.Xml.Serialization
Imports System.Xml.Schema

Public Class Group
   <SoapAttribute (Namespace:= "http:'www.cpandl.com")> _
   Public GroupName As String 
   
   <SoapAttribute(DataType:= "base64Binary")> _
   Public GroupNumber() As Byte

   <SoapAttribute(DataType:= "date", _
   AttributeName:= "CreationDate")> _
   Public Today As DateTime 
   <SoapElement(DataType:= "nonNegativeInteger", _
   ElementName:= "PosInt")> _
   Public PostitiveInt As String 
   ' This is ignored when serialized unless it's overridden.
   <SoapIgnore> _ 
   Public IgnoreThis As Boolean 
   
   Public Grouptype As GroupType 

   Public MyVehicle As Vehicle 

   '  The SoapInclude allows the method to return a Car.
   <SoapInclude(GetType(Car))> _
   Public Function myCar(licNumber As String ) As Vehicle 
      Dim v As Vehicle 
      if licNumber = "" Then
         v = New Car()
         v.licenseNumber = "!!!!!!"
      else  
       v = New Car()
       v.licenseNumber = licNumber
      End If
      
      return v
   End Function
End Class
  
' SoapInclude allows Vehicle to accept Car type.
<SoapInclude(GetType(Car))> _
Public MustInherit  class Vehicle
   Public licenseNumber As String 
   Public makeDate As DateTime 
End Class

Public Class Car
   Inherits Vehicle

End Class

Public enum GroupType
   ' These enums can be overridden.
   <SoapEnum("Small")> _
   A
   <SoapEnum("Large")> _ 
   B
End Enum
 
Public Class Run

   Shared Sub Main()
      Dim test As Run = New Run()
      test.SerializeOriginal("SoapOriginal.xml")
      test.SerializeOverride("SoapOverrides.xml")
      test.DeserializeOriginal("SoapOriginal.xml")
      test.DeserializeOverride("SoapOverrides.xml")
   End SUb
   
   Public Sub SerializeOriginal(filename As String)

      ' Create an instance of the XmlSerializer class.
      Dim myMapping As XmlTypeMapping = _
      (New SoapReflectionImporter().ImportTypeMapping _
      (GetType(Group)))
      Dim mySerializer As XmlSerializer =  _
      New XmlSerializer(myMapping)
      
      Dim myGroup As Group =MakeGroup()
      ' Writing the file requires a TextWriter.
      Dim writer As XmlTextWriter  = _
      New XmlTextWriter(filename, Encoding.UTF8)
      writer.Formatting = Formatting.Indented
      writer.WriteStartElement("wrapper")
      ' Serialize the class, and close the TextWriter.
      mySerializer.Serialize(writer, myGroup)
      writer.WriteEndElement()
      writer.Close()
   End Sub

   Public Sub SerializeOverride(filename As String)
      ' Create an instance of the XmlSerializer class
      ' that overrides the serialization.
      Dim overRideSerializer As XmlSerializer = _
      CreateOverrideSerializer()
      Dim myGroup As Group =MakeGroup()
      ' Writing the file requires a TextWriter.
      Dim writer As XmlTextWriter  = _
      New XmlTextWriter(filename, Encoding.UTF8)
      writer.Formatting = Formatting.Indented
      writer.WriteStartElement("wrapper")
      ' Serialize the class, and close the TextWriter.
      overRideSerializer.Serialize(writer, myGroup)
      writer.WriteEndElement()
      writer.Close()
    End Sub

   private Function MakeGroup() As Group 
      ' Create an instance of the class that will be serialized.
      Dim myGroup As Group  = New Group()

      ' Set the object properties.
      myGroup.GroupName = ".NET"

      Dim hexByte()As Byte = new Byte(1){Convert.ToByte(100), _
      Convert.ToByte(50)}
      myGroup.GroupNumber = hexByte

      Dim myDate As DateTime  = new DateTime(2002,5,2)
      myGroup.Today = myDate

      myGroup.PostitiveInt = "10000"
    myGroup.IgnoreThis = true
    myGroup.Grouptype = GroupType.B
    Dim thisCar As Car 
    thisCar =CType(myGroup.myCar("1234566"), Car)
    myGroup.myVehicle=thisCar
      return myGroup
   End Function   	

   Public Sub DeserializeOriginal(filename As String)
      ' Create an instance of the XmlSerializer class.
      Dim myMapping As XmlTypeMapping = _
      (New SoapReflectionImporter().ImportTypeMapping _
      (GetType(Group)))
      Dim mySerializer As XmlSerializer =  _
      New XmlSerializer(myMapping)

      ' Reading the file requires an  XmlTextReader.
      Dim reader As XmlTextReader = _
      New XmlTextReader(filename)
      reader.ReadStartElement("wrapper")

      ' Deserialize and cast the object.
      Dim myGroup As Group  = _
      CType(mySerializer.Deserialize(reader), Group)
      reader.ReadEndElement()
      reader.Close()
   End Sub

   Public Sub DeserializeOverride(filename As String)
      ' Create an instance of the XmlSerializer class.
      Dim overRideSerializer As XmlSerializer  = _
      CreateOverrideSerializer()

      ' Reading the file requires an  XmlTextReader.
      Dim reader As XmlTextReader = _
      New XmlTextReader(filename)
      reader.ReadStartElement("wrapper")

      ' Deserialize and cast the object.
      Dim myGroup As Group = _
      CType(overRideSerializer.Deserialize(reader), Group)
      reader.ReadEndElement()
      reader.Close()
      ReadGroup(myGroup)
   End Sub

   private Sub ReadGroup(myGroup As Group)
      Console.WriteLine(myGroup.GroupName)
      Console.WriteLine(myGroup.GroupNumber(0))
      Console.WriteLine(myGroup.GroupNumber(1))
      Console.WriteLine(myGroup.Today)
      Console.WriteLine(myGroup.PostitiveInt)
      Console.WriteLine(myGroup.IgnoreThis)
      Console.WriteLine()
   End Sub
   
   Private Function CreateOverrideSerializer() As XmlSerializer
      Dim soapOver As SoapAttributeOverrides = New SoapAttributeOverrides()
      Dim soapAtts As SoapAttributes = New SoapAttributes()

      Dim mySoapElement As SoapElementAttribute = New SoapElementAttribute()
      mySoapElement.ElementName = "xxxx"
      soapAtts.SoapElement = mySoapElement
      soapOver.Add(GetType(Group), "PostitiveInt", soapAtts)

      ' Override the IgnoreThis property.
      Dim myIgnore As SoapIgnoreAttribute  = new SoapIgnoreAttribute()
      soapAtts = New SoapAttributes()
      soapAtts.SoapIgnore = false
      soapOver.Add(GetType(Group), "IgnoreThis", soapAtts)

      ' Override the GroupType enumeration.
      soapAtts = New SoapAttributes()
      Dim xSoapEnum As SoapEnumAttribute = new SoapEnumAttribute()
      xSoapEnum.Name = "Over1000"
      soapAtts.SoapEnum = xSoapEnum
      ' Add the SoapAttributes to the SoapOverrides object.
      soapOver.Add(GetType(GroupType), "A", soapAtts)

      ' Create second enumeration and add it.
      soapAtts = New SoapAttributes()
      xSoapEnum = New SoapEnumAttribute()
      xSoapEnum.Name = "ZeroTo1000"
      soapAtts.SoapEnum = xSoapEnum
      soapOver.Add(GetType(GroupType), "B", soapAtts)

      ' Override the Group type.
      soapAtts = New SoapAttributes()
      Dim soapType As SoapTypeAttribute = New SoapTypeAttribute()
      soapType.TypeName = "Team"
      soapAtts.SoapType = soapType
      soapOver.Add(GetType(Group),soapAtts)
    
      Dim myMapping As XmlTypeMapping = (New SoapReflectionImporter( _
      soapOver)).ImportTypeMapping(GetType(Group))
    
       Dim ser As XmlSerializer = new XmlSerializer(myMapping)
      return ser
   End Function
End Class

설명

이 생성자는 개체를 SOAP 메시지로 serialize 할 때 XmlSerializer을 만드는 데 사용 됩니다.This constructor is used to create an XmlSerializer when you serialize an object into a SOAP message. 생성 되는 SOAP 메시지를 제어 하려면 System.Xml.Serialization 네임 스페이스에 있는 특수 특성 ("Soap"로 시작)을 사용 합니다.To control the SOAP messages generated, use the special attributes (beginning with the word "Soap") found in the System.Xml.Serialization namespace.

추가 정보

XmlSerializer(Type, String)

지정된 형식의 개체를 XML 문서로 직렬화하고 XML 문서를 지정된 형식의 개체로 역직렬화할 수 있는 XmlSerializer 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into objects of the specified type. 모든 XML 요소에 대 한 기본 네임 스페이스를 지정합니다.Specifies the default namespace for all the XML elements.

public:
 XmlSerializer(Type ^ type, System::String ^ defaultNamespace);
public XmlSerializer (Type type, string defaultNamespace);
new System.Xml.Serialization.XmlSerializer : Type * string -> System.Xml.Serialization.XmlSerializer
Public Sub New (type As Type, defaultNamespace As String)

매개 변수

type
Type

XmlSerializer가 serialize할 수 있는 개체의 형식입니다.The type of the object that this XmlSerializer can serialize.

defaultNamespace
String

모든 XML 요소에 사용할 기본 네임 스페이스입니다.The default namespace to use for all the XML elements.

예제

다음 예제에서는 Widget이라는 개체를 serialize 하는 XmlSerializer를 생성 합니다.The following example constructs an XmlSerializer that serializes an object named Widget. 이 예제에서는 Serialize 메서드를 호출 하기 전에 개체의 다양 한 속성을 설정 합니다.The example sets various properties of the object before calling the Serialize method.

private:
   void SerializeObject( String^ filename )
   {
      XmlSerializer^ serializer = gcnew XmlSerializer(
         OrderedItem::typeid,"http://www.cpandl.com" );

      // Create an instance of the class to be serialized.
      OrderedItem^ i = gcnew OrderedItem;

      // Insert code to set property values.

      // Writing the document requires a TextWriter.
      TextWriter^ writer = gcnew StreamWriter( filename );
      // Serialize the object, and close the TextWriter
      serializer->Serialize( writer, i );
      writer->Close();
   }

   void DeserializeObject( String^ filename )
   {
      XmlSerializer^ serializer = gcnew XmlSerializer(
         OrderedItem::typeid,"http://www.cpandl.com" );
      // A FileStream is needed to read the XML document.
      FileStream^ fs = gcnew FileStream( filename,FileMode::Open );

      // Declare an object variable of the type to be deserialized.
      OrderedItem^ i;

      // Deserialize the object.
      i = dynamic_cast<OrderedItem^>(serializer->Deserialize( fs ));

      // Insert code to use the properties and methods of the object.
   }
   private void SerializeObject(string filename) {
       XmlSerializer serializer = new XmlSerializer
           (typeof(OrderedItem), "http://www.cpandl.com");
        
       // Create an instance of the class to be serialized.
       OrderedItem i = new OrderedItem();
        
       // Insert code to set property values.
        
       // Writing the document requires a TextWriter.
       TextWriter writer = new StreamWriter(filename);
       // Serialize the object, and close the TextWriter
       serializer.Serialize(writer, i);
       writer.Close();
   }

   private void DeserializeObject(string filename) {
       XmlSerializer serializer = new XmlSerializer
           (typeof(OrderedItem), "http://www.cpandl.com");
       // A FileStream is needed to read the XML document.
       FileStream fs = new FileStream(filename, FileMode.Open);
        
       // Declare an object variable of the type to be deserialized.
       OrderedItem i;
        
       // Deserialize the object.
       i = (OrderedItem) serializer.Deserialize(fs);
        
       // Insert code to use the properties and methods of the object.
   }

Private Sub SerializeObject(ByVal filename As String)
    Dim serializer As New XmlSerializer(GetType(OrderedItem), _
                                          "http://www.cpandl.com")
    
    ' Create an instance of the class to be serialized.
    Dim i As New OrderedItem()
    
    ' Insert code to set property values.
    ' Writing the document requires a TextWriter.
    Dim writer As New StreamWriter(filename)
    ' Serialize the object, and close the TextWriter.
    serializer.Serialize(writer, i)
    writer.Close()
End Sub


Private Sub DeserializeObject(ByVal filename As String)
    Dim serializer As New XmlSerializer(GetType(OrderedItem), _
                                          "http://www.cpandl.com")
    ' A FileStream is needed to read the XML document.
    Dim fs As New FileStream(filename, FileMode.Open)
    
    ' Declare an object variable of the type to be deserialized.
    Dim i As OrderedItem
    
    ' Deserialize the object.
    i = CType(serializer.Deserialize(fs), OrderedItem)
    ' Insert code to use the properties and methods of the object.
End Sub
     

추가 정보

XmlSerializer(Type, Type[])

지정된 형식의 개체를 XML 문서로 직렬화하고 XML 문서를 지정된 형식의 개체로 역직렬화할 수 있는 XmlSerializer 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into object of a specified type. 필드 또는 속성이 배열을 반환하는 경우 extraTypes 매개 변수는 배열에 삽입될 수 있는 개체를 지정합니다.If a property or field returns an array, the extraTypes parameter specifies objects that can be inserted into the array.

public:
 XmlSerializer(Type ^ type, cli::array <Type ^> ^ extraTypes);
public XmlSerializer (Type type, Type[] extraTypes);
new System.Xml.Serialization.XmlSerializer : Type * Type[] -> System.Xml.Serialization.XmlSerializer
Public Sub New (type As Type, extraTypes As Type())

매개 변수

type
Type

XmlSerializer가 serialize할 수 있는 개체의 형식입니다.The type of the object that this XmlSerializer can serialize.

extraTypes
Type[]

serialize할 추가 개체 형식으로 이루어진 Type 배열입니다.A Type array of additional object types to serialize.

예제

다음 예제에서는 개체의 배열을 반환 하는 공용 필드를 포함 하는 클래스의 인스턴스를 serialize 합니다.The following example serializes an instance of a class that contains a public field that returns an array of objects. XmlSerializer 생성자의 extraTypes 매개 변수는 배열에서 serialize 할 수 있는 개체의 형식을 지정 합니다.The extraTypes parameter of the XmlSerializer constructor specifies the types of the objects that can be serialized in the array.

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

using namespace System;
using namespace System::IO;
using namespace System::Xml;
using namespace System::Xml::Serialization;
ref class Address;
ref class Phone;

// This defines the object that will be serialized.
public ref class Teacher
{
public:
   String^ Name;
   Teacher(){}

   /* Note that the Info field returns an array of objects.
         Any object can be added to the array by adding the
         object type to the array passed to the extraTypes argument. */

   [XmlArray(ElementName="ExtraInfo",IsNullable=true)]
   array<Object^>^Info;
   Phone^ PhoneInfo;
};


// This defines one of the extra types to be included.
public ref class Address
{
public:
   String^ City;
   Address(){}

   Address( String^ city )
   {
      City = city;
   }
};

// Another extra type to include.
public ref class Phone
{
public:
   String^ PhoneNumber;
   Phone(){}

   Phone( String^ phoneNumber )
   {
      PhoneNumber = phoneNumber;
   }
};

// Another type, derived from Phone
public ref class InternationalPhone: public Phone
{
public:
   String^ CountryCode;
   InternationalPhone(){}

   InternationalPhone( String^ countryCode )
   {
      CountryCode = countryCode;
   }
};

public ref class Run
{
public:
   static void main()
   {
      Run^ test = gcnew Run;
      test->SerializeObject( "Teacher.xml" );
      test->DeserializeObject( "Teacher.xml" );
   }

private:
   void SerializeObject( String^ filename )
   {
      // Writing the file requires a TextWriter.
      TextWriter^ myStreamWriter = gcnew StreamWriter( filename );

      // Create a Type array.
      array<Type^>^extraTypes = gcnew array<Type^>(3);
      extraTypes[ 0 ] = Address::typeid;
      extraTypes[ 1 ] = Phone::typeid;
      extraTypes[ 2 ] = InternationalPhone::typeid;

      // Create the XmlSerializer instance.
      XmlSerializer^ mySerializer = gcnew XmlSerializer( Teacher::typeid,extraTypes );
      Teacher^ teacher = gcnew Teacher;
      teacher->Name = "Mike";

      // Add extra types to the Teacher object
      array<Object^>^info = gcnew array<Object^>(2);
      info[ 0 ] = gcnew Address( "Springville" );
      info[ 1 ] = gcnew Phone( "555-0100" );
      teacher->Info = info;
      teacher->PhoneInfo = gcnew InternationalPhone( "000" );
      mySerializer->Serialize( myStreamWriter, teacher );
      myStreamWriter->Close();
   }

   void DeserializeObject( String^ filename )
   {
      // Create a Type array.
      array<Type^>^extraTypes = gcnew array<Type^>(3);
      extraTypes[ 0 ] = Address::typeid;
      extraTypes[ 1 ] = Phone::typeid;
      extraTypes[ 2 ] = InternationalPhone::typeid;

      // Create the XmlSerializer instance.
      XmlSerializer^ mySerializer = gcnew XmlSerializer( Teacher::typeid,extraTypes );

      // Reading a file requires a FileStream.
      FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
      Teacher^ teacher = dynamic_cast<Teacher^>(mySerializer->Deserialize( fs ));

      // Read the extra information.
      Address^ a = dynamic_cast<Address^>(teacher->Info[ 0 ]);
      Phone^ p = dynamic_cast<Phone^>(teacher->Info[ 1 ]);
      InternationalPhone^ Ip = dynamic_cast<InternationalPhone^>(teacher->PhoneInfo);
      Console::WriteLine( teacher->Name );
      Console::WriteLine( a->City );
      Console::WriteLine( p->PhoneNumber );
      Console::WriteLine( Ip->CountryCode );
   }
};

int main()
{
   Run::main();
}
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

// This defines the object that will be serialized.
public class Teacher
{  
   public string Name;
   public Teacher(){}
   /* Note that the Info field returns an array of objects.
      Any object can be added to the array by adding the
      object type to the array passed to the extraTypes argument. */
   [XmlArray (ElementName = "ExtraInfo", IsNullable = true)]
   public object[] Info;
   public Phone PhoneInfo;
}
 
// This defines one of the extra types to be included.
public class Address
{  
   public string City;

   public Address(){}
   public Address(string city)
   {
      City = city;
   }
}

// Another extra type to include.
public class Phone
{
   public string PhoneNumber;
   public Phone(){}
   public Phone(string phoneNumber)
   {
      PhoneNumber = phoneNumber;
   }
}

// Another type, derived from Phone
public class InternationalPhone:Phone
{
   public string CountryCode;

   public InternationalPhone(){}

   public InternationalPhone(string countryCode)
   {
      CountryCode = countryCode;
   }
}
    
public class Run
{
   public static void Main()
   {
      Run test = new Run();
      test.SerializeObject("Teacher.xml");
      test.DeserializeObject("Teacher.xml");
   }
 
   private void SerializeObject(string filename)
   {
      // Writing the file requires a TextWriter.
      TextWriter myStreamWriter = new StreamWriter(filename);
 
      // Create a Type array.
      Type [] extraTypes= new Type[3];
      extraTypes[0] = typeof(Address);
      extraTypes[1] = typeof(Phone);
      extraTypes[2] = typeof(InternationalPhone);

      // Create the XmlSerializer instance.
      XmlSerializer mySerializer = new XmlSerializer
      (typeof(Teacher),extraTypes);
          
      Teacher teacher = new Teacher();
      teacher.Name = "Mike";
      // Add extra types to the Teacher object
      object [] info = new object[2];
      info[0] = new Address("Springville");
      info[1] = new Phone("555-0100");
         
      teacher.Info = info;

      teacher.PhoneInfo = new InternationalPhone("000"); 

      mySerializer.Serialize(myStreamWriter,teacher);
      myStreamWriter.Close();
   }
 
   private void DeserializeObject(string filename)
   {
      // Create a Type array.
      Type [] extraTypes= new Type[3];
      extraTypes[0] = typeof(Address);
      extraTypes[1] = typeof(Phone);
      extraTypes[2] = typeof(InternationalPhone);

      // Create the XmlSerializer instance.
      XmlSerializer mySerializer = new XmlSerializer
      (typeof(Teacher),extraTypes);
      
      // Reading a file requires a FileStream.
      FileStream fs = new FileStream(filename, FileMode.Open);
      Teacher teacher = (Teacher) mySerializer.Deserialize(fs);
         
      // Read the extra information.
      Address a = (Address)teacher.Info[0];
      Phone p = (Phone) teacher.Info[1];
      InternationalPhone Ip = 
      (InternationalPhone) teacher.PhoneInfo;

      Console.WriteLine(teacher.Name);
      Console.WriteLine(a.City);
      Console.WriteLine(p.PhoneNumber);
      Console.WriteLine(Ip.CountryCode);
   }
}
Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization



' This defines the object that will be serialized.
Public Class Teacher
    Public Name As String
    
    Public Sub New()
    End Sub
    ' Note that the Info field returns an array of objects.
    ' Any object can be added to the array by adding the
    ' object type to the array passed to the extraTypes argument. 
    <XmlArray(ElementName := "ExtraInfo", IsNullable := True)> _
    Public Info() As Object
    Public PhoneInfo As Phone
End Class


' This defines one of the extra types to be included.
Public Class Address
    Public City As String
    
    Public Sub New()
    End Sub
    
    Public Sub New(city As String)
        me.City = city
    End Sub
End Class
 

' Another extra type to include.
Public Class Phone
    Public PhoneNumber As String
    
    Public Sub New()
    End Sub
    
    Public Sub New(phoneNumber As String)
        me.PhoneNumber = phoneNumber
    End Sub
End Class


' Another type, derived from Phone.
Public Class InternationalPhone
    Inherits Phone
    Public CountryCode As String
    
    
    Public Sub New()
    End Sub
     
    Public Sub New(countryCode As String)
        me.CountryCode = countryCode
    End Sub
End Class


Public Class Run
    
    Public Shared Sub Main()
        Dim test As New Run()
        test.SerializeObject("Teacher.xml")
        test.DeserializeObject("Teacher.xml")
    End Sub
    
    
    Private Sub SerializeObject(filename As String)
        ' Writing the file requires a TextWriter.
        Dim myStreamWriter As New StreamWriter(filename)
        
        ' Create a Type array.
        Dim extraTypes(2) As Type
        extraTypes(0) = GetType(Address)
        extraTypes(1) = GetType(Phone)
        extraTypes(2) = GetType(InternationalPhone)
        
        ' Create the XmlSerializer instance.
        Dim mySerializer As New XmlSerializer(GetType(Teacher), extraTypes)
        
        Dim teacher As New Teacher()
        teacher.Name = "Mike"
        ' Add extra types to the Teacher object.
        Dim info(1) As Object
        info(0) = New Address("Springville")
        info(1) = New Phone("555-0100")
        
        teacher.Info = info
        
        teacher.PhoneInfo = New InternationalPhone("000")
        
        mySerializer.Serialize(myStreamWriter, teacher)
        myStreamWriter.Close()
    End Sub
    
    
    Private Sub DeserializeObject(filename As String)
        ' Create a Type array.
        Dim extraTypes(2) As Type
        extraTypes(0) = GetType(Address)
        extraTypes(1) = GetType(Phone)
        extraTypes(2) = GetType(InternationalPhone)
        
        ' Create the XmlSerializer instance.
        Dim mySerializer As New XmlSerializer(GetType(Teacher), extraTypes)
        
        ' Reading a file requires a FileStream.
        Dim fs As New FileStream(filename, FileMode.Open)
        Dim teacher As Teacher = CType(mySerializer.Deserialize(fs), Teacher)
        
        ' Read the extra information.
        Dim a As Address = CType(teacher.Info(0), Address)
        Dim p As Phone = CType(teacher.Info(1), Phone)
        Dim Ip As InternationalPhone = CType(teacher.PhoneInfo, InternationalPhone)
        
        Console.WriteLine(teacher.Name)
        Console.WriteLine(a.City)
        Console.WriteLine(p.PhoneNumber)
        Console.WriteLine(Ip.CountryCode)
    End Sub
End Class

설명

기본적으로 공용 속성 또는 필드 개체의 배열 또는 개체를 반환 하는 경우 개체 유형은 자동으로 serialize 됩니다.By default, if a public property or field returns an object, or array of objects, the object types are automatically serialized. 그러나 클래스에 Object형식의 배열을 반환 하는 필드 또는 속성이 포함 되어 있으면 해당 배열에 개체를 삽입할 수 있습니다.However, if a class contains a field or property that returns an array of type Object, any object can be inserted into that array. 이 경우 XmlSerializer Object 배열에 삽입 되는 모든 가능한 개체 형식을 예상 하도록 지시 해야 합니다.In that case, the XmlSerializer must be instructed to expect all the possible object types that are inserted into the Object array. 이렇게 하려면 extraTypes 매개 변수를 사용 하 여 serialize 하거나 deserialize 할 추가 개체 유형을 지정 합니다.To do this, use the extraTypes parameter to specify the extra object types to serialize or deserialize.

또한 extraTypes 매개 변수를 사용 하 여 기본 클래스에서 파생 된 형식을 지정할 수 있습니다.You can also use the extraTypes parameter to specify types derived from a base class. 예를 들어 Phone 이라는 기본 클래스가 있고 InternationalPhone 라는 클래스가이 클래스에서 파생 된다고 가정 합니다.For example, suppose a base class named Phone exists, and a class named InternationalPhone derives from it. 파생 형식도 지정 하려면 extraTypes 매개 변수를 사용 합니다.Use the extraTypes parameter to specify the derived type as well.

추가 정보

XmlSerializer(Type, XmlAttributeOverrides)

지정된 형식의 개체를 XML 문서로 직렬화하고 XML 문서를 지정된 형식의 개체로 역직렬화할 수 있는 XmlSerializer 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into objects of the specified type. Serialize 될 각 개체를 포함할 수 있으며이 오버 로드는 다른 클래스를 사용 하 여 재정의할 수 있는 클래스의 인스턴스.Each object to be serialized can itself contain instances of classes, which this overload can override with other classes.

public:
 XmlSerializer(Type ^ type, System::Xml::Serialization::XmlAttributeOverrides ^ overrides);
public XmlSerializer (Type type, System.Xml.Serialization.XmlAttributeOverrides overrides);
new System.Xml.Serialization.XmlSerializer : Type * System.Xml.Serialization.XmlAttributeOverrides -> System.Xml.Serialization.XmlSerializer
Public Sub New (type As Type, overrides As XmlAttributeOverrides)

매개 변수

type
Type

직렬화할 개체의 형식입니다.The type of the object to serialize.

예제

다음 예제에서는 이렇게 하려면 DLL에 정의 된 DLL에 있는 공용 멤버를 재정의 하는 클래스의 인스턴스를 serialize 합니다.The following example serializes an instance of a class that is defined in a DLL and to do so, overrides the public members found in the DLL.

// Beginning of HighSchool.dll
#using <System.Xml.dll>
#using <System.dll>

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

namespace HighSchool
{
   public ref class Student
   {
   public:
      String^ Name;
      int ID;
   };

   public ref class MyClass
   {
   public:
      array<Student^>^Students;
   };
}

namespace College
{

using namespace HighSchool;
   public ref class Graduate: public HighSchool::Student
   {
   public:
      Graduate(){}

      // Add a new field named University.
      String^ University;
   };

   public ref class Run
   {
   public:
      static void main()
      {
         Run^ test = gcnew Run;
         test->WriteOverriddenAttributes( "College.xml" );
         test->ReadOverriddenAttributes( "College.xml" );
      }

   private:
      void WriteOverriddenAttributes( String^ filename )
      {
         // Writing the file requires a TextWriter.
         TextWriter^ myStreamWriter = gcnew StreamWriter( filename );

         // Create an XMLAttributeOverrides class.
         XmlAttributeOverrides^ attrOverrides = gcnew XmlAttributeOverrides;

         // Create the XmlAttributes class.
         XmlAttributes^ attrs = gcnew XmlAttributes;

         /* Override the Student class. "Alumni" is the name
               of the overriding element in the XML output. */
         XmlElementAttribute^ attr = gcnew XmlElementAttribute( "Alumni",Graduate::typeid );

         /* Add the XmlElementAttribute to the collection of
               elements in the XmlAttributes object. */
         attrs->XmlElements->Add( attr );

         /* Add the XmlAttributes to the XmlAttributeOverrides. 
               "Students" is the name being overridden. */
         attrOverrides->Add( HighSchool::MyClass::typeid, "Students", attrs );

         // Create the XmlSerializer. 
         XmlSerializer^ mySerializer = gcnew XmlSerializer( HighSchool::MyClass::typeid,attrOverrides );
         MyClass ^ myClass = gcnew MyClass;
         Graduate^ g1 = gcnew Graduate;
         g1->Name = "Jackie";
         g1->ID = 1;
         g1->University = "Alma Mater";
         Graduate^ g2 = gcnew Graduate;
         g2->Name = "Megan";
         g2->ID = 2;
         g2->University = "CM";
         array<Student^>^myArray = {g1,g2};
         myClass->Students = myArray;
         mySerializer->Serialize( myStreamWriter, myClass );
         myStreamWriter->Close();
      }

      void ReadOverriddenAttributes( String^ filename )
      {
         /* The majority of the code here is the same as that in the
               WriteOverriddenAttributes method. Because the XML being read
               doesn't conform to the schema defined by the DLL, the
               XMLAttributesOverrides must be used to create an 
               XmlSerializer instance to read the XML document.*/
         XmlAttributeOverrides^ attrOverrides = gcnew XmlAttributeOverrides;
         XmlAttributes^ attrs = gcnew XmlAttributes;
         XmlElementAttribute^ attr = gcnew XmlElementAttribute( "Alumni",Graduate::typeid );
         attrs->XmlElements->Add( attr );
         attrOverrides->Add( HighSchool::MyClass::typeid, "Students", attrs );
         XmlSerializer^ readSerializer = gcnew XmlSerializer( HighSchool::MyClass::typeid,attrOverrides );
         
         // To read the file, a FileStream object is required. 
         FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
         MyClass ^ myClass;
         myClass = dynamic_cast<MyClass^>(readSerializer->Deserialize( fs ));

         /* Here is the difference between reading and writing an 
               XML document: You must declare an object of the derived 
               type (Graduate) and cast the Student instance to it.*/
         Graduate^ g;
         System::Collections::IEnumerator^ myEnum = myClass->Students->GetEnumerator();
         while ( myEnum->MoveNext() )
         {
            Graduate^ grad = safe_cast<Graduate^>(myEnum->Current);
            g = dynamic_cast<Graduate^>(grad);
            Console::Write( "{0}\t", g->Name );
            Console::Write( "{0}\t", g->ID );
            Console::Write( "{0}\n", g->University );
         }
      }
   };
}

int main()
{
   College::Run::main();
}
// Beginning of HighSchool.dll
namespace HighSchool
{
   public class Student
   {
      public string Name;
      public int ID;
   }
    
   public class MyClass
   {
      public Student[] Students;
   }
}

namespace College
   {
   using System;
   using System.IO;
   using System.Xml;
   using System.Xml.Serialization; 
   using HighSchool;

    public class Graduate:HighSchool.Student
    {
       public Graduate(){}
       // Add a new field named University.
       public string University;
    }

   public class Run
   {
      public static void Main()
      {
         Run test = new Run();
         test.WriteOverriddenAttributes("College.xml");
         test.ReadOverriddenAttributes("College.xml");
      }
 
      private void WriteOverriddenAttributes(string filename)
      {
         // Writing the file requires a TextWriter.
         TextWriter myStreamWriter = new StreamWriter(filename);
         // Create an XMLAttributeOverrides class.
         XmlAttributeOverrides attrOverrides = 
         new XmlAttributeOverrides();
         // Create the XmlAttributes class.
         XmlAttributes attrs = new XmlAttributes();

         /* Override the Student class. "Alumni" is the name
         of the overriding element in the XML output. */
         XmlElementAttribute attr = 
         new XmlElementAttribute("Alumni", typeof(Graduate));

         /* Add the XmlElementAttribute to the collection of
         elements in the XmlAttributes object. */
         attrs.XmlElements.Add(attr);

         /* Add the XmlAttributes to the XmlAttributeOverrides. 
         "Students" is the name being overridden. */
         attrOverrides.Add(typeof(HighSchool.MyClass), 
         "Students", attrs);
          
         // Create the XmlSerializer. 
         XmlSerializer mySerializer = new XmlSerializer
         (typeof(HighSchool.MyClass), attrOverrides);
 
         MyClass myClass = new MyClass();

         Graduate g1 = new Graduate();
         g1.Name = "Jackie";
         g1.ID = 1;
         g1.University = "Alma Mater";

         Graduate g2 = new Graduate();
         g2.Name = "Megan";
         g2.ID = 2;
         g2.University = "CM";

         Student[] myArray = {g1,g2};
         myClass.Students = myArray;
 
         mySerializer.Serialize(myStreamWriter, myClass);
         myStreamWriter.Close();
      }

      private void ReadOverriddenAttributes(string filename)
      {
         /* The majority of the code here is the same as that in the
         WriteOverriddenAttributes method. Because the XML being read
         doesn't conform to the schema defined by the DLL, the
         XMLAttributesOverrides must be used to create an 
         XmlSerializer instance to read the XML document.*/
          
         XmlAttributeOverrides attrOverrides = new 
         XmlAttributeOverrides();
         XmlAttributes attrs = new XmlAttributes();
         XmlElementAttribute attr = 
         new XmlElementAttribute("Alumni", typeof(Graduate));
         attrs.XmlElements.Add(attr);
         attrOverrides.Add(typeof(HighSchool.MyClass), 
         "Students", attrs);

         XmlSerializer readSerializer = new XmlSerializer
         (typeof(HighSchool.MyClass), attrOverrides);

         // To read the file, a FileStream object is required. 
         FileStream fs = new FileStream(filename, FileMode.Open);
          
         MyClass myClass;

         myClass = (MyClass) readSerializer.Deserialize(fs);

         /* Here is the difference between reading and writing an 
         XML document: You must declare an object of the derived 
         type (Graduate) and cast the Student instance to it.*/
         Graduate g;

         foreach(Graduate grad in myClass.Students)
         {
            g = (Graduate) grad;
            Console.Write(g.Name + "\t");
            Console.Write(g.ID + "\t");
            Console.Write(g.University + "\n");
         }
      }
   }
}
' Beginning of HighSchool.dll
Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization
Imports HighSchool

Namespace HighSchool
    
    Public Class Student
        Public Name As String
        Public ID As Integer
    End Class
    
    
    Public Class MyClass1
        Public Students() As Student
    End Class
End Namespace 'HighSchool

Namespace College
    Public Class Graduate
        Inherits HighSchool.Student
        
        Public Sub New()
        End Sub
        Public University As String
    End Class
    
    
    
    Public Class Run
        
        Public Shared Sub Main()
            Dim test As New Run()
            test.WriteOverriddenAttributes("College.xml")
            test.ReadOverriddenAttributes("College.xml")
        End Sub
        
        
        Private Sub WriteOverriddenAttributes(filename As String)
            ' Writing the file requires a TextWriter.
            Dim myStreamWriter As New StreamWriter(filename)
            ' Create an XMLAttributeOverrides class.
            Dim attrOverrides As New XmlAttributeOverrides()
            ' Create the XmlAttributes class.
            Dim attrs As New XmlAttributes()
            
            ' Override the Student class. "Alumni" is the name
            ' of the overriding element in the XML output. 
            Dim attr As New XmlElementAttribute("Alumni", GetType(Graduate))
            
            ' Add the XmlElementAttribute to the collection of
            ' elements in the XmlAttributes object. 
            attrs.XmlElements.Add(attr)
            
            ' Add the XmlAttributes to the XmlAttributeOverrides. 
            ' "Students" is the name being overridden. 
            attrOverrides.Add(GetType(HighSchool.MyClass1), "Students", attrs)
            
            ' Create the XmlSerializer. 
            Dim mySerializer As New XmlSerializer(GetType(HighSchool.MyClass1), attrOverrides)
            
            Dim oMyClass As New MyClass1()
            
            Dim g1 As New Graduate()
            g1.Name = "Jackie"
            g1.ID = 1
            g1.University = "Alma Mater"
            
            Dim g2 As New Graduate()
            g2.Name = "Megan"
            g2.ID = 2
            g2.University = "CM"
            
            Dim myArray As Student() =  {g1, g2}
            oMyClass.Students = myArray
            
            mySerializer.Serialize(myStreamWriter, oMyClass)
            myStreamWriter.Close()
        End Sub
        
        
        Private Sub ReadOverriddenAttributes(filename As String)
            ' The majority of the code here is the same as that in the
            ' WriteOverriddenAttributes method. Because the XML being read
            ' doesn't conform to the schema defined by the DLL, the
            ' XMLAttributesOverrides must be used to create an
            ' XmlSerializer instance to read the XML document.
            
            Dim attrOverrides As New XmlAttributeOverrides()
            Dim attrs As New XmlAttributes()
            Dim attr As New XmlElementAttribute("Alumni", GetType(Graduate))
            attrs.XmlElements.Add(attr)
            attrOverrides.Add(GetType(HighSchool.MyClass1), "Students", attrs)
            
            Dim readSerializer As New XmlSerializer(GetType(HighSchool.MyClass1), attrOverrides)
            
            ' To read the file, a FileStream object is required. 
            Dim fs As New FileStream(filename, FileMode.Open)
            
            Dim oMyClass As MyClass1
            
            oMyClass = CType(readSerializer.Deserialize(fs), MyClass1)
            
            ' Here is the difference between reading and writing an
            ' XML document: You must declare an object of the derived
            ' type (Graduate) and cast the Student instance to it.
            Dim g As Graduate
            
            Dim grad As Graduate
            For Each grad In  oMyClass.Students
                g = CType(grad, Graduate)
                Console.Write((g.Name & ControlChars.Tab))
                Console.Write((g.ID.ToString & ControlChars.Tab))
                Console.Write((g.University & ControlChars.Cr))
            Next grad
        End Sub
    End Class
End Namespace 'College

설명

overrides 매개 변수를 사용 하 여 필드와 속성이 XML로 인코딩 되는 방법을 제어할 수 있습니다.The overrides parameter can be used to control how fields and properties are encoded in XML. 이러한 설정은 개체에 이미 존재 하는 모든 특성을 재정의 합니다.These settings override any attributes that already exist on the objects. 이 기능은 소스 코드를 수정할 수 없습니다 또는 여러 인코딩 동일한 클래스에 대 한 필요한 경우에 유용할 수 있습니다.This can be useful when the source code cannot be modified or multiple encodings are required for the same classes.

추가 정보

XmlSerializer(Type, XmlRootAttribute)

지정된 형식의 개체를 XML 문서로 직렬화하고 XML 문서를 지정된 형식의 개체로 역직렬화할 수 있는 XmlSerializer 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize an XML document into object of the specified type. 또한 XML 루트 요소로 사용할 클래스를 지정 합니다.It also specifies the class to use as the XML root element.

public:
 XmlSerializer(Type ^ type, System::Xml::Serialization::XmlRootAttribute ^ root);
public XmlSerializer (Type type, System.Xml.Serialization.XmlRootAttribute root);
new System.Xml.Serialization.XmlSerializer : Type * System.Xml.Serialization.XmlRootAttribute -> System.Xml.Serialization.XmlSerializer
Public Sub New (type As Type, root As XmlRootAttribute)

매개 변수

type
Type

XmlSerializer가 serialize할 수 있는 개체의 형식입니다.The type of the object that this XmlSerializer can serialize.

root
XmlRootAttribute

XML 루트 요소를 나타내는 XmlRootAttribute입니다.An XmlRootAttribute that represents the XML root element.

예제

다음 예제에서는 네임 스페이스 및 요소 이름과 같이 XML 루트 요소의 다양 한 속성을 포함 하는 XmlRootAttribute를 사용 하는 XmlSerializer를 생성 합니다.The following example constructs an XmlSerializer that uses an XmlRootAttribute that contains various properties of the XML root element, such as its namespace and element name.

private:
   void SerializeObject( String^ filename )
   {
      // Create an XmlRootAttribute, and set its properties.
      XmlRootAttribute^ xRoot = gcnew XmlRootAttribute;
      xRoot->ElementName = "CustomRoot";
      xRoot->Namespace = "http://www.cpandl.com";
      xRoot->IsNullable = true;

      // Construct the XmlSerializer with the XmlRootAttribute.
      XmlSerializer^ serializer = gcnew XmlSerializer(
         OrderedItem::typeid,xRoot );

      // Create an instance of the object to serialize.
      OrderedItem^ i = gcnew OrderedItem;
      // Insert code to set properties of the ordered item.

      // Writing the document requires a TextWriter.
      TextWriter^ writer = gcnew StreamWriter( filename );
      serializer->Serialize( writer, i );
      writer->Close();
   }

   void DeserializeObject( String^ filename )
   {
      // Create an XmlRootAttribute, and set its properties.
      XmlRootAttribute^ xRoot = gcnew XmlRootAttribute;
      xRoot->ElementName = "CustomRoot";
      xRoot->Namespace = "http://www.cpandl.com";
      xRoot->IsNullable = true;

      XmlSerializer^ serializer = gcnew XmlSerializer(
         OrderedItem::typeid,xRoot );

      // A FileStream is needed to read the XML document.
      FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
      // Deserialize the object.
      OrderedItem^ i = dynamic_cast<OrderedItem^>(serializer->Deserialize( fs ));
      // Insert code to use the object's properties and methods.
   }
private void SerializeObject(string filename) {
    // Create an XmlRootAttribute, and set its properties.
    XmlRootAttribute xRoot = new XmlRootAttribute();
    xRoot.ElementName = "CustomRoot";
    xRoot.Namespace = "http://www.cpandl.com";
    xRoot.IsNullable = true;
     
    // Construct the XmlSerializer with the XmlRootAttribute.
    XmlSerializer serializer = new XmlSerializer
        (typeof(OrderedItem),xRoot);
     
    // Create an instance of the object to serialize.
    OrderedItem i = new OrderedItem();
    // Insert code to set properties of the ordered item.
     
    // Writing the document requires a TextWriter.
    TextWriter writer = new StreamWriter(filename);
     
    serializer.Serialize(writer, i);
    writer.Close();
}

private void DeserializeObject(string filename) {
    // Create an XmlRootAttribute, and set its properties.
    XmlRootAttribute xRoot = new XmlRootAttribute();
    xRoot.ElementName = "CustomRoot";
    xRoot.Namespace = "http://www.cpandl.com";
    xRoot.IsNullable = true;
     
    XmlSerializer serializer = new XmlSerializer
        (typeof(OrderedItem),xRoot);
     
    // A FileStream is needed to read the XML document.
    FileStream fs = new FileStream(filename, FileMode.Open);
    // Deserialize the object.
    OrderedItem i = (OrderedItem) serializer.Deserialize(fs);
    // Insert code to use the object's properties and methods.
}

Private Sub SerializeObject(ByVal filename As String)
    ' Create an XmlRootAttribute, and set its properties.
    Dim xRoot As New XmlRootAttribute()
    xRoot.ElementName = "CustomRoot"
    xRoot.Namespace = "http://www.cpandl.com"
    xRoot.IsNullable = True
    
    ' Construct the XmlSerializer with the XmlRootAttribute.
    Dim serializer As New XmlSerializer(GetType(OrderedItem), xRoot)
    
    ' Create an instance of the object to serialize.
    Dim i As New OrderedItem()
    ' Insert code to set properties of the ordered item.
    ' Writing the document requires a TextWriter.
    Dim writer As New StreamWriter(filename)
    
    serializer.Serialize(writer, i)
    writer.Close()
End Sub
    
Private Sub DeserializeObject(ByVal filename As String)
    ' Create an XmlRootAttribute, and set its properties.
    Dim xRoot As New XmlRootAttribute()
    xRoot.ElementName = "CustomRoot"
    xRoot.Namespace = "http://www.cpandl.com"
    xRoot.IsNullable = True
    
    Dim serializer As New XmlSerializer(GetType(OrderedItem), xRoot)
    
    ' A FileStream is needed to read the XML document.
    Dim fs As New FileStream(filename, FileMode.Open)
    ' Deserialize the object.
    Dim i As OrderedItem = CType(serializer.Deserialize(fs), OrderedItem)
    ' Insert code to use the object's properties and methods.
End Sub
     

설명

XML 문서의 루트 요소는 다른 모든 요소를 포함합니다.The root element of an XML document encloses all the other elements. 기본적으로 type 매개 변수로 지정 된 개체는 루트 요소로 serialize 됩니다.By default, the object specified by the type parameter is serialized as the root element. Root 요소의 XML 요소 이름과 같은 속성은 type 개체에서 가져옵니다.Properties, such as the XML element name of the root element, are taken from the type object. 그러나 root 매개 변수를 사용 하면 XmlRootAttribute를 지정 하 여 기본 개체의 정보를 바꿀 수 있습니다. 개체를 사용 하 여 다른 네임 스페이스, 요소 이름 등을 설정할 수 있습니다.However, the root parameter allows you to replace the default object's information by specifying an XmlRootAttribute; the object allows you to set a different namespace, element name, and so on.

추가 정보

XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String)

XmlSerializer 형식의 개체를 XML 문서 인스턴스로 직렬화하고 XML 문서 인스턴스를 Object 형식의 개체로 역직렬화할 수 있는 Object 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the XmlSerializer class that can serialize objects of type Object into XML document instances, and deserialize XML document instances into objects of type Object. Serialize 될 각 개체를 포함할 수 있으며이 오버 로드를 다른 클래스로 재정의 하는 클래스의 인스턴스.Each object to be serialized can itself contain instances of classes, which this overload overrides with other classes. 또한이 오버 로드는 모든 XML 요소 및 XML 루트 요소로 사용 하는 클래스에 대 한 기본 네임 스페이스를 지정 합니다.This overload also specifies the default namespace for all the XML elements and the class to use as the XML root element.

public:
 XmlSerializer(Type ^ type, System::Xml::Serialization::XmlAttributeOverrides ^ overrides, cli::array <Type ^> ^ extraTypes, System::Xml::Serialization::XmlRootAttribute ^ root, System::String ^ defaultNamespace);
public XmlSerializer (Type type, System.Xml.Serialization.XmlAttributeOverrides overrides, Type[] extraTypes, System.Xml.Serialization.XmlRootAttribute root, string defaultNamespace);
new System.Xml.Serialization.XmlSerializer : Type * System.Xml.Serialization.XmlAttributeOverrides * Type[] * System.Xml.Serialization.XmlRootAttribute * string -> System.Xml.Serialization.XmlSerializer
Public Sub New (type As Type, overrides As XmlAttributeOverrides, extraTypes As Type(), root As XmlRootAttribute, defaultNamespace As String)

매개 변수

type
Type

XmlSerializer가 serialize할 수 있는 개체의 형식입니다.The type of the object that this XmlSerializer can serialize.

overrides
XmlAttributeOverrides

XmlAttributeOverrides 매개 변수에 지정된 클래스의 동작을 확장하거나 재정의하는 type입니다.An XmlAttributeOverrides that extends or overrides the behavior of the class specified in the type parameter.

extraTypes
Type[]

serialize할 추가 개체 형식으로 이루어진 Type 배열입니다.A Type array of additional object types to serialize.

root
XmlRootAttribute

XML 요소 속성을 정의하는 XmlRootAttribute입니다.An XmlRootAttribute that defines the XML root element properties.

defaultNamespace
String

XML 문서에 있는 모든 XML 요소의 기본 네임스페이스입니다.The default namespace of all XML elements in the XML document.

예제

다음 예제에서는 이렇게 하려면 DLL에 정의 된 클래스에 public 멤버를 재정의 하는 클래스의 인스턴스를 serialize 합니다.The following example serializes an instance of a class that is defined in a DLL and to do so, overrides the public members found in the class. 예제에는 또한 추가 유형, 모든 XML 요소 및 XML 루트 요소 정보를 제공 하는 클래스를 사용 하 여 기본 네임 스페이스 배열을 지정 합니다.The example also specifies an array of extra types, the default namespace for all XML elements, and the class to use that provides the XML root element information. 이 예제에서는 시작 부분에 있는 코드를 HighSchool라는 DLL로 컴파일 했다고 가정 합니다.The example assumes that the code at the beginning has been compiled into a DLL named HighSchool.

// Beginning of the HighSchool.dll 
#using <System.Xml.dll>
#using <System.dll>

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

namespace HighSchool
{
   public ref class Student
   {
   public:
      String^ Name;
      int ID;
   };

   public ref class MyClass
   {
   public:
      array<Student^>^Students;
   };
}

namespace College
{

using namespace HighSchool;
   public ref class Graduate: public HighSchool::Student
   {
   public:
      Graduate(){}

      // Add a new field named University.
      String^ University;

      // Use extra types to use this field.
      array<Object^>^Info;
   };

   public ref class Address
   {
   public:
      String^ City;
   };

   public ref class Phone
   {
   public:
      String^ Number;
   };

   public ref class Run
   {
   public:
      static void main()
      {
         Run^ test = gcnew Run;
         test->WriteOverriddenAttributes( "College.xml" );
         test->ReadOverriddenAttributes( "College.xml" );
      }

   private:
      void WriteOverriddenAttributes( String^ filename )
      {
         // Writing the file requires a TextWriter.
         TextWriter^ myStreamWriter = gcnew StreamWriter( filename );

         // Create an XMLAttributeOverrides class.
         XmlAttributeOverrides^ attrOverrides = gcnew XmlAttributeOverrides;

         // Create the XmlAttributes class.
         XmlAttributes^ attrs = gcnew XmlAttributes;

         /* Override the Student class. "Alumni" is the name
               of the overriding element in the XML output. */
         XmlElementAttribute^ attr = gcnew XmlElementAttribute( "Alumni",Graduate::typeid );

         /* Add the XmlElementAttribute to the collection of
               elements in the XmlAttributes object. */
         attrs->XmlElements->Add( attr );

         /* Add the XmlAttributes to the XmlAttributeOverrides. 
               "Students" is the name being overridden. */
         attrOverrides->Add( HighSchool::MyClass::typeid, "Students", attrs );

         // Create array of extra types.
         array<Type^>^extraTypes = gcnew array<Type^>(2);
         extraTypes[ 0 ] = Address::typeid;
         extraTypes[ 1 ] = Phone::typeid;

         // Create an XmlRootAttribute.
         XmlRootAttribute^ root = gcnew XmlRootAttribute( "Graduates" );

         /* Create the XmlSerializer with the 
               XmlAttributeOverrides object. */
         XmlSerializer^ mySerializer = gcnew XmlSerializer( HighSchool::MyClass::typeid,attrOverrides,extraTypes,root,"http://www.microsoft.com" );
         MyClass ^ myClass = gcnew MyClass;
         Graduate^ g1 = gcnew Graduate;
         g1->Name = "Jacki";
         g1->ID = 1;
         g1->University = "Alma";
         Graduate^ g2 = gcnew Graduate;
         g2->Name = "Megan";
         g2->ID = 2;
         g2->University = "CM";
         array<Student^>^myArray = {g1,g2};
         myClass->Students = myArray;

         // Create extra information.
         Address^ a1 = gcnew Address;
         a1->City = "Ionia";
         Address^ a2 = gcnew Address;
         a2->City = "Stamford";
         Phone^ p1 = gcnew Phone;
         p1->Number = "555-0101";
         Phone^ p2 = gcnew Phone;
         p2->Number = "555-0100";
         array<Object^>^o1 = {a1,p1};
         array<Object^>^o2 = {a2,p2};
         g1->Info = o1;
         g2->Info = o2;
         mySerializer->Serialize( myStreamWriter, myClass );
         myStreamWriter->Close();
      }

      void ReadOverriddenAttributes( String^ filename )
      {
         /* The majority of the code here is the same as that in the
               WriteOverriddenAttributes method. Because the XML being read
               doesn't conform to the schema defined by the DLL, the
               XMLAttributesOverrides must be used to create an 
               XmlSerializer instance to read the XML document.*/
         XmlAttributeOverrides^ attrOverrides = gcnew XmlAttributeOverrides;
         XmlAttributes^ attrs = gcnew XmlAttributes;
         XmlElementAttribute^ attr = gcnew XmlElementAttribute( "Alumni",Graduate::typeid );
         attrs->XmlElements->Add( attr );
         attrOverrides->Add( HighSchool::MyClass::typeid, "Students", attrs );
         array<Type^>^extraTypes = gcnew array<Type^>(2);
         extraTypes[ 0 ] = Address::typeid;
         extraTypes[ 1 ] = Phone::typeid;
         XmlRootAttribute^ root = gcnew XmlRootAttribute( "Graduates" );
         XmlSerializer^ readSerializer = gcnew XmlSerializer( HighSchool::MyClass::typeid,attrOverrides,extraTypes,root,"http://www.microsoft.com" );

         // A FileStream object is required to read the file. 
         FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
         MyClass ^ myClass;
         myClass = dynamic_cast<MyClass^>(readSerializer->Deserialize( fs ));
         
         /* Here is the difference between reading and writing an 
               XML document: You must declare an object of the derived 
               type (Graduate) and cast the Student instance to it.*/
         Graduate^ g;
         Address^ a;
         Phone^ p;
         System::Collections::IEnumerator^ myEnum = myClass->Students->GetEnumerator();
         while ( myEnum->MoveNext() )
         {
            Graduate^ grad = safe_cast<Graduate^>(myEnum->Current);
            g = dynamic_cast<Graduate^>(grad);
            Console::Write( "{0}\t", g->Name );
            Console::Write( "{0}\t", g->ID );
            Console::Write( "{0}\n", g->University );
            a = dynamic_cast<Address^>(g->Info[ 0 ]);
            Console::WriteLine( a->City );
            p = dynamic_cast<Phone^>(g->Info[ 1 ]);
            Console::WriteLine( p->Number );
         }
      }
   };
}

int main()
{
   College::Run::main();
}
// Beginning of the HighSchool.dll 

namespace HighSchool
{
   public class Student
   {
      public string Name;
      public int ID;
   }
    
   public class MyClass
   {
      public Student[] Students;
   }
}

namespace College
   {
   using System;
   using System.IO;
   using System.Xml;
   using System.Xml.Serialization; 
   using HighSchool;

    public class Graduate:HighSchool.Student
    {
       public Graduate(){}
       // Add a new field named University.
       public string University;
       // Use extra types to use this field.
       public object[]Info;
    }
 
    public class Address
    {
       public string City;
    }
 
    public class Phone
    {
       public string Number;
    }
    
   public class Run
   {
      public static void Main()
      {
         Run test = new Run();
         test.WriteOverriddenAttributes("College.xml");
         test.ReadOverriddenAttributes("College.xml");
      }
 
      private void WriteOverriddenAttributes(string filename)
      {
         // Writing the file requires a TextWriter.
         TextWriter myStreamWriter = new StreamWriter(filename);
         // Create an XMLAttributeOverrides class.
         XmlAttributeOverrides attrOverrides = 
         new XmlAttributeOverrides();
         // Create the XmlAttributes class.
         XmlAttributes attrs = new XmlAttributes();
         /* Override the Student class. "Alumni" is the name
         of the overriding element in the XML output. */

         XmlElementAttribute attr = 
         new XmlElementAttribute("Alumni", typeof(Graduate));
         /* Add the XmlElementAttribute to the collection of
         elements in the XmlAttributes object. */
         attrs.XmlElements.Add(attr);
         /* Add the XmlAttributes to the XmlAttributeOverrides. 
         "Students" is the name being overridden. */
         attrOverrides.Add(typeof(HighSchool.MyClass), 
         "Students", attrs);
 
         // Create array of extra types.
         Type [] extraTypes = new Type[2];
         extraTypes[0]=typeof(Address);
         extraTypes[1]=typeof(Phone);
 
         // Create an XmlRootAttribute.
         XmlRootAttribute root = new XmlRootAttribute("Graduates");
          
         /* Create the XmlSerializer with the 
         XmlAttributeOverrides object. */
         XmlSerializer mySerializer = new XmlSerializer
         (typeof(HighSchool.MyClass), attrOverrides, extraTypes,
         root, "http://www.microsoft.com");
 
         MyClass myClass= new MyClass();

         Graduate g1 = new Graduate();
         g1.Name = "Jacki";
         g1.ID = 1;
         g1.University = "Alma";

         Graduate g2 = new Graduate();
         g2.Name = "Megan";
         g2.ID = 2;
         g2.University = "CM";

         Student[] myArray = {g1,g2};

         myClass.Students = myArray;
 
         // Create extra information.
         Address a1 = new Address();
         a1.City = "Ionia";
         Address a2 = new Address();
         a2.City = "Stamford";
         Phone p1 = new Phone();
         p1.Number = "555-0101";
         Phone p2 = new Phone();
         p2.Number = "555-0100";
 
         Object[]o1 = new Object[2]{a1, p1};
         Object[]o2 = new Object[2]{a2,p2};
 
         g1.Info = o1;
         g2.Info = o2;
         mySerializer.Serialize(myStreamWriter,myClass);
         myStreamWriter.Close();
      }

      private void ReadOverriddenAttributes(string filename)
      {
         /* The majority of the code here is the same as that in the
         WriteOverriddenAttributes method. Because the XML being read
         doesn't conform to the schema defined by the DLL, the
         XMLAttributesOverrides must be used to create an 
         XmlSerializer instance to read the XML document.*/
          
         XmlAttributeOverrides attrOverrides = new 
         XmlAttributeOverrides();
         XmlAttributes attrs = new XmlAttributes();
         XmlElementAttribute attr = 
         new XmlElementAttribute("Alumni", typeof(Graduate));
         attrs.XmlElements.Add(attr);
         attrOverrides.Add(typeof(HighSchool.MyClass), 
         "Students", attrs);

         Type [] extraTypes = new Type[2];
         extraTypes[0] = typeof(Address);
         extraTypes[1] = typeof(Phone);
 
         XmlRootAttribute root = new XmlRootAttribute("Graduates");
          
         XmlSerializer readSerializer = new XmlSerializer
         (typeof(HighSchool.MyClass), attrOverrides, extraTypes,
         root, "http://www.microsoft.com");

         // A FileStream object is required to read the file. 
         FileStream fs = new FileStream(filename, FileMode.Open);
          
         MyClass myClass;
         myClass = (MyClass) readSerializer.Deserialize(fs);

         /* Here is the difference between reading and writing an 
         XML document: You must declare an object of the derived 
         type (Graduate) and cast the Student instance to it.*/
         Graduate g;
         Address a;
         Phone p;
         foreach(Graduate grad in myClass.Students)
         {
            g = (Graduate) grad;
            Console.Write(g.Name + "\t");
            Console.Write(g.ID + "\t");
            Console.Write(g.University + "\n");
            a = (Address) g.Info[0];
            Console.WriteLine(a.City);
            p = (Phone) g.Info[1];
            Console.WriteLine(p.Number);
         }
      }
   }
}
'Beginning of the HighSchool.dll 
Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization

' Imports HighSchool

Namespace HighSchool

    Public Class Student
        Public Name As String
        Public ID As Integer
    End Class


    Public Class ClassRoom
        Public Students() As Student
    End Class
End Namespace 'HighSchool

Namespace College
    Public Class Graduate
        Inherits HighSchool.Student

        Public Sub New()
        End Sub
        ' Add a new field named University.
        Public University As String
        ' Use extra types to use this field.
        Public Info() As Object
    End Class


    Public Class Address
        Public City As String
    End Class


    Public Class Phone
        Public Number As String
    End Class


    Public Class Run

        Public Shared Sub Main()
            Dim test As New Run()
            test.WriteOverriddenAttributes("College.xml")
            test.ReadOverriddenAttributes("College.xml")
        End Sub


        Private Sub WriteOverriddenAttributes(ByVal filename As String)
            ' Writing the file requires a TextWriter.
            Dim myStreamWriter As New StreamWriter(filename)
            ' Create an XMLAttributeOverrides class.
            Dim attrOverrides As New XmlAttributeOverrides()
            ' Create the XmlAttributes class.
            Dim attrs As New XmlAttributes()
            ' Override the Student class. "Alumni" is the name
            ' of the overriding element in the XML output. 

            Dim attr As New XmlElementAttribute("Alumni", GetType(Graduate))
            ' Add the XmlElementAttribute to the collection of
            ' elements in the XmlAttributes object. 
            attrs.XmlElements.Add(attr)
            ' Add the XmlAttributes to the XmlAttributeOverrides.
            ' "Students" is the name being overridden. 
            attrOverrides.Add(GetType(HighSchool.ClassRoom), "Students", attrs)

            ' Create array of extra types.
            Dim extraTypes(1) As Type
            extraTypes(0) = GetType(Address)
            extraTypes(1) = GetType(Phone)

            ' Create an XmlRootAttribute.
            Dim root As New XmlRootAttribute("Graduates")

            ' Create the XmlSerializer with the
            ' XmlAttributeOverrides object. 
            Dim mySerializer As New XmlSerializer(GetType(HighSchool.ClassRoom), _
                attrOverrides, extraTypes, root, "http://www.microsoft.com")

            Dim oMyClass As New HighSchool.ClassRoom()

            Dim g1 As New Graduate()
            g1.Name = "Jacki"
            g1.ID = 1
            g1.University = "Alma"

            Dim g2 As New Graduate()
            g2.Name = "Megan"
            g2.ID = 2
            g2.University = "CM"

            Dim myArray As HighSchool.Student() = {g1, g2}

            oMyClass.Students = myArray

            ' Create extra information.
            Dim a1 As New Address()
            a1.City = "Ionia"
            Dim a2 As New Address()
            a2.City = "Stamford"
            Dim p1 As New Phone()
            p1.Number = "555-0101"
            Dim p2 As New Phone()
            p2.Number = "555-0100"

            Dim o1() As Object = {a1, p1}
            Dim o2() As Object = {a2, p2}

            g1.Info = o1
            g2.Info = o2
            mySerializer.Serialize(myStreamWriter, oMyClass)
            myStreamWriter.Close()
        End Sub


        Private Sub ReadOverriddenAttributes(ByVal filename As String)
            ' The majority of the code here is the same as that in the
            ' WriteOverriddenAttributes method. Because the XML being read
            ' doesn't conform to the schema defined by the DLL, the
            ' XMLAttributesOverrides must be used to create an
            ' XmlSerializer instance to read the XML document.

            Dim attrOverrides As New XmlAttributeOverrides()
            Dim attrs As New XmlAttributes()
            Dim attr As New XmlElementAttribute("Alumni", GetType(Graduate))
            attrs.XmlElements.Add(attr)
            attrOverrides.Add(GetType(HighSchool.ClassRoom), "Students", attrs)

            Dim extraTypes(1) As Type
            extraTypes(0) = GetType(Address)
            extraTypes(1) = GetType(Phone)

            Dim root As New XmlRootAttribute("Graduates")

            Dim readSerializer As New XmlSerializer(GetType(HighSchool.ClassRoom), _
                attrOverrides, extraTypes, root, "http://www.microsoft.com")

            ' A FileStream object is required to read the file. 
            Dim fs As New FileStream(filename, FileMode.Open)

            Dim oMyClass As HighSchool.ClassRoom
            oMyClass = CType(readSerializer.Deserialize(fs), HighSchool.ClassRoom)

            ' Here is the difference between reading and writing an
            ' XML document: You must declare an object of the derived
            ' type (Graduate) and cast the Student instance to it.
            Dim g As Graduate
            Dim a As Address
            Dim p As Phone
            Dim grad As Graduate
            For Each grad In oMyClass.Students
                g = CType(grad, Graduate)
                Console.Write((g.Name & ControlChars.Tab))
                Console.Write((g.ID & ControlChars.Tab))
                Console.Write((g.University & ControlChars.Cr))
                a = CType(g.Info(0), Address)
                Console.WriteLine(a.City)
                p = CType(g.Info(1), Phone)
                Console.WriteLine(p.Number)
            Next grad
        End Sub
    End Class
End Namespace 'College

설명

overrides 매개 변수를 사용 하면 기본 클래스의 동작을 확장 하거나 재정의 하는 클래스를 serialize 하는 [XmlSerializer 생성자 (Type, XmlAttributeOverrides, Type<f: System.xml >를 만들 수 있습니다.The overrides parameter allows for the creation of an [XmlSerializer Constructor (Type, XmlAttributeOverrides, Type<xref:System.Xml.Serialization.XmlSerializer> that serializes a class that extends or overrides the behavior of a base class. 예를 들어, DLL 들어 수 있기 상속 하거나 DLL에 포함 된 클래스를 확장 하는 클래스를 만듭니다.For example, given a DLL, it is possible to create a class that inherits or extends a class contained in the DLL. 이러한 클래스를 serialize 하려면 [xmlserializer 생성자 (type, xmlattributeoverrides, type<f: f >를 생성할 때 [XmlSerializer 생성자 (Type, XmlAttributeOverrides, type<>: 클래스의 인스턴스를 사용 해야 합니다.To serialize such a class, you must use an instance of the [XmlSerializer Constructor (Type, XmlAttributeOverrides, Type<xref:System.Xml.Serialization.XmlAttributeOverrides> class when constructing the [XmlSerializer Constructor (Type, XmlAttributeOverrides, Type<xref:System.Xml.Serialization.XmlSerializer>. 자세한 내용은 [XmlSerializer 생성자 (Type, XmlAttributeOverrides, Type<f: System.xml 재정의 >를 참조 하세요.For more details, see [XmlSerializer Constructor (Type, XmlAttributeOverrides, Type<xref:System.Xml.Serialization.XmlAttributeOverrides>.

기본적으로 공용 속성 또는 필드 개체의 배열 또는 개체를 반환 하는 경우 개체 유형은 자동으로 serialize 됩니다.By default, if a public property or field returns an object, or array of objects, the object types are automatically serialized. 그러나 클래스에 [XmlSerializer 생성자 (Type, XmlAttributeOverrides, Type<f: System.object > 형식의 배열을 반환 하는 필드 또는 속성이 포함 된 경우 모든 개체를 해당 배열에 삽입할 수 있습니다.However, if a class contains a field or property that returns an array of type [XmlSerializer Constructor (Type, XmlAttributeOverrides, Type<xref:System.Object>, any object can be inserted into that array. 이 경우 [xmlserializer 생성자 (Type, XmlAttributeOverrides, Type<f: f >에 삽입 되는 모든 가능한 개체 형식을 [XmlSerializer 생성자 (Type, XmlAttributeOverrides, Type<: System.object > 배열에 예상 하도록 지시 해야 합니다.In that case, the [XmlSerializer Constructor (Type, XmlAttributeOverrides, Type<xref:System.Xml.Serialization.XmlSerializer> must be instructed to expect all the possible object types that are inserted into the [XmlSerializer Constructor (Type, XmlAttributeOverrides, Type<xref:System.Object> array. 이렇게 하려면 extraTypes 매개 변수를 사용 하 여 serialize 하거나 deserialize 할 추가 개체 유형을 지정 합니다.To do this, use the extraTypes parameter to specify the extra object types to serialize or deserialize.

XML 문서의 루트 요소는 다른 모든 요소를 포함합니다.The root element of an XML document encloses all the other elements. 기본적으로 type 매개 변수로 지정 된 개체는 루트 요소로 serialize 됩니다.By default, the object specified by the type parameter is serialized as the root element. Root 요소의 XML 요소 이름과 같은 속성은 type 개체에서 가져옵니다.Properties, such as the XML element name of the root element are taken from the type object. 그러나 root 매개 변수를 사용 하면 [XmlSerializer 생성자 (Type, XmlAttributeOverrides, Type<f: Xmlrootattribute가 >를 지정 하 여 기본 개체의 정보를 바꿀 수 있습니다 .이 개체를 사용 하 여 다른 네임 스페이스, 요소 이름 등을 설정할 수 있습니다.However, the root parameter allows you to replace the default object's information by specifying an [XmlSerializer Constructor (Type, XmlAttributeOverrides, Type<xref:System.Xml.Serialization.XmlRootAttribute>; the object allows you to set a different namespace, element name, and so on.

defaultName 매개 변수를 사용 하 여 [XmlSerializer 생성자 (Type, XmlAttributeOverrides, Type<f: System.xml >에서 생성 되는 모든 XML 요소의 기본 네임 스페이스를 지정 합니다.Use the defaultName parameter to specify the default namespace of all XML elements generated by the [XmlSerializer Constructor (Type, XmlAttributeOverrides, Type<xref:System.Xml.Serialization.XmlSerializer>.

추가 정보

XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String)

XmlSerializer 형식의 개체를 XML 문서 인스턴스로 직렬화하고 XML 문서 인스턴스를 Object 형식의 개체로 역직렬화할 수 있는 Object 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the XmlSerializer class that can serialize objects of type Object into XML document instances, and deserialize XML document instances into objects of type Object. Serialize 될 각 개체를 포함할 수 있으며이 오버 로드를 다른 클래스로 재정의 하는 클래스의 인스턴스.Each object to be serialized can itself contain instances of classes, which this overload overrides with other classes. 또한이 오버 로드는 모든 XML 요소 및 XML 루트 요소로 사용 하는 클래스에 대 한 기본 네임 스페이스를 지정 합니다.This overload also specifies the default namespace for all the XML elements and the class to use as the XML root element.

public:
 XmlSerializer(Type ^ type, System::Xml::Serialization::XmlAttributeOverrides ^ overrides, cli::array <Type ^> ^ extraTypes, System::Xml::Serialization::XmlRootAttribute ^ root, System::String ^ defaultNamespace, System::String ^ location);
public XmlSerializer (Type type, System.Xml.Serialization.XmlAttributeOverrides overrides, Type[] extraTypes, System.Xml.Serialization.XmlRootAttribute root, string defaultNamespace, string location);
new System.Xml.Serialization.XmlSerializer : Type * System.Xml.Serialization.XmlAttributeOverrides * Type[] * System.Xml.Serialization.XmlRootAttribute * string * string -> System.Xml.Serialization.XmlSerializer
Public Sub New (type As Type, overrides As XmlAttributeOverrides, extraTypes As Type(), root As XmlRootAttribute, defaultNamespace As String, location As String)

매개 변수

type
Type

XmlSerializer가 serialize할 수 있는 개체의 형식입니다.The type of the object that this XmlSerializer can serialize.

overrides
XmlAttributeOverrides

XmlAttributeOverrides 매개 변수에 지정된 클래스의 동작을 확장하거나 재정의하는 type입니다.An XmlAttributeOverrides that extends or overrides the behavior of the class specified in the type parameter.

extraTypes
Type[]

serialize할 추가 개체 형식으로 이루어진 Type 배열입니다.A Type array of additional object types to serialize.

root
XmlRootAttribute

XML 요소 속성을 정의하는 XmlRootAttribute입니다.An XmlRootAttribute that defines the XML root element properties.

defaultNamespace
String

XML 문서에 있는 모든 XML 요소의 기본 네임스페이스입니다.The default namespace of all XML elements in the XML document.

location
String

형식의 위치입니다.The location of the types.

XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String, Evidence)

경고

이 API는 현재 사용되지 않습니다.

지정된 형식의 개체를 XML 문서 인스턴스로 직렬화하고 XML 문서 인스턴스를 지정된 형식의 개체로 역직렬화할 수 있는 XmlSerializer 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML document instances, and deserialize XML document instances into objects of the specified type. 이 오버 로드를 사용 하면 기본 네임 스페이스를 모든 XML 요소에 대 한 XML 루트 요소, 위치 및 액세스에 필요한 자격 증명으로 사용 하는 클래스 뿐만 아니라 작업을 serialization 또는 deserialization 중에 발생할 수 있는 다른 유형과 제공할 수 있습니다. .This overload allows you to supply other types that can be encountered during a serialization or deserialization operation, as well as a default namespace for all XML elements, the class to use as the XML root element, its location, and credentials required for access.

public:
 XmlSerializer(Type ^ type, System::Xml::Serialization::XmlAttributeOverrides ^ overrides, cli::array <Type ^> ^ extraTypes, System::Xml::Serialization::XmlRootAttribute ^ root, System::String ^ defaultNamespace, System::String ^ location, System::Security::Policy::Evidence ^ evidence);
public XmlSerializer (Type type, System.Xml.Serialization.XmlAttributeOverrides overrides, Type[] extraTypes, System.Xml.Serialization.XmlRootAttribute root, string defaultNamespace, string location, System.Security.Policy.Evidence evidence);
[System.Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. Please use a XmlSerializer constructor overload which does not take an Evidence parameter. See http://go2.microsoft.com/fwlink/?LinkId=131738 for more information.")]
public XmlSerializer (Type type, System.Xml.Serialization.XmlAttributeOverrides overrides, Type[] extraTypes, System.Xml.Serialization.XmlRootAttribute root, string defaultNamespace, string location, System.Security.Policy.Evidence evidence);
new System.Xml.Serialization.XmlSerializer : Type * System.Xml.Serialization.XmlAttributeOverrides * Type[] * System.Xml.Serialization.XmlRootAttribute * string * string * System.Security.Policy.Evidence -> System.Xml.Serialization.XmlSerializer
Public Sub New (type As Type, overrides As XmlAttributeOverrides, extraTypes As Type(), root As XmlRootAttribute, defaultNamespace As String, location As String, evidence As Evidence)

매개 변수

type
Type

XmlSerializer가 serialize할 수 있는 개체의 형식입니다.The type of the object that this XmlSerializer can serialize.

overrides
XmlAttributeOverrides

XmlAttributeOverrides 매개 변수에 지정된 클래스의 동작을 확장하거나 재정의하는 type입니다.An XmlAttributeOverrides that extends or overrides the behavior of the class specified in the type parameter.

extraTypes
Type[]

serialize할 추가 개체 형식으로 이루어진 Type 배열입니다.A Type array of additional object types to serialize.

root
XmlRootAttribute

XML 요소 속성을 정의하는 XmlRootAttribute입니다.An XmlRootAttribute that defines the XML root element properties.

defaultNamespace
String

XML 문서에 있는 모든 XML 요소의 기본 네임스페이스입니다.The default namespace of all XML elements in the XML document.

location
String

형식의 위치입니다.The location of the types.

evidence
Evidence

형식에 액세스하는 데 필요한 자격 증명이 포함된 Evidence 클래스의 인스턴스입니다.An instance of the Evidence class that contains credentials required to access types.

특성

설명

임시 디렉터리에 대 한 액세스를 보다 정밀 하 게 제어할 수 있습니다 하 고 코드 주입 및 악용을 방지 합니다.Allows more precise control over access to a temporary directory and prevents code injection and exploitation. 이 메서드를 사용 하려면 위치를 지정 하 고 특정 사용자 에게만 액세스 권한을 부여 합니다.To use this method, specify a location and give access only to specific users. 관리자 권한을 증명 정보와 일치 하는 증명 정보 목록 사용 하 여 정책을 설정할 수 있습니다.Administrators can set up policies with evidence lists that match evidence to permissions.

적용 대상