XmlSerializer 클래스

정의

XML 문서로 개체를 직렬화하고 XML 문서에서 개체를 역직렬화합니다. XmlSerializer를 사용하면 개체가 XML로 인코딩되는 방식을 제어할 수 있습니다.

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

예제

다음 예제에는 및 Test의 두 가지 기본 클래스가 포함되어 있습니다PurchaseOrder. 클래스에는 PurchaseOrder 단일 구매에 대한 정보가 포함되어 있습니다. 클래스에는 Test 구매 주문을 만들고 만든 구매 주문을 읽는 메서드가 포함되어 있습니다.

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

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

/* The XmlRootAttribute allows you to set an alternate name 
   (PurchaseOrder) of the XML element, the element namespace; by 
   default, the XmlSerializer uses the class name. The attribute 
   also allows you to set the XML namespace for the element.  Lastly,
   the attribute sets the IsNullable property, which specifies whether 
   the xsi:null attribute appears if the class instance is set to 
   a null reference. */

[XmlRootAttribute("PurchaseOrder",Namespace="http://www.cpandl.com",
IsNullable=false)]
public ref class PurchaseOrder
{
public:
   Address^ ShipTo;
   String^ OrderDate;

   /* The XmlArrayAttribute changes the XML element name
       from the default of "OrderedItems" to "Items". */

   [XmlArrayAttribute("Items")]
   array<OrderedItem^>^OrderedItems;
   Decimal SubTotal;
   Decimal ShipCost;
   Decimal TotalCost;
};

public ref class Address
{
public:

   /* The XmlAttribute instructs the XmlSerializer to serialize the Name
         field as an XML attribute instead of an XML element (the default
         behavior). */

   [XmlAttributeAttribute]
   String^ Name;
   String^ Line1;

   /* Setting the IsNullable property to false instructs the 
         XmlSerializer that the XML attribute will not appear if 
         the City field is set to a null reference. */

   [XmlElementAttribute(IsNullable=false)]
   String^ City;
   String^ State;
   String^ Zip;
};

public ref class OrderedItem
{
public:
   String^ ItemName;
   String^ Description;
   Decimal UnitPrice;
   int Quantity;
   Decimal LineTotal;

   /* Calculate is a custom method that calculates the price per item,
         and stores the value in a field. */
   void Calculate()
   {
      LineTotal = UnitPrice * Quantity;
   }

};

public ref class Test
{
public:
   static void main()
   {
      // Read and write purchase orders.
      Test^ t = gcnew Test;
      t->CreatePO( "po.xml" );
      t->ReadPO( "po.xml" );
   }

private:
   void CreatePO( String^ filename )
   {
      // Create an instance of the XmlSerializer class;
      // specify the type of object to serialize.
      XmlSerializer^ serializer = gcnew XmlSerializer( PurchaseOrder::typeid );
      TextWriter^ writer = gcnew StreamWriter( filename );
      PurchaseOrder^ po = gcnew PurchaseOrder;

      // Create an address to ship and bill to.
      Address^ billAddress = gcnew Address;
      billAddress->Name = "Teresa Atkinson";
      billAddress->Line1 = "1 Main St.";
      billAddress->City = "AnyTown";
      billAddress->State = "WA";
      billAddress->Zip = "00000";

      // Set ShipTo and BillTo to the same addressee.
      po->ShipTo = billAddress;
      po->OrderDate = System::DateTime::Now.ToLongDateString();

      // Create an OrderedItem object.
      OrderedItem^ i1 = gcnew OrderedItem;
      i1->ItemName = "Widget S";
      i1->Description = "Small widget";
      i1->UnitPrice = (Decimal)5.23;
      i1->Quantity = 3;
      i1->Calculate();

      // Insert the item into the array.
      array<OrderedItem^>^items = {i1};
      po->OrderedItems = items;

      // Calculate the total cost.
      Decimal subTotal = Decimal(0);
      System::Collections::IEnumerator^ myEnum = items->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         OrderedItem^ oi = safe_cast<OrderedItem^>(myEnum->Current);
         subTotal = subTotal + oi->LineTotal;
      }

      po->SubTotal = subTotal;
      po->ShipCost = (Decimal)12.51;
      po->TotalCost = po->SubTotal + po->ShipCost;

      // Serialize the purchase order, and close the TextWriter.
      serializer->Serialize( writer, po );
      writer->Close();
   }

protected:
   void ReadPO( String^ filename )
   {
      // Create an instance of the XmlSerializer class;
      // specify the type of object to be deserialized.
      XmlSerializer^ serializer = gcnew XmlSerializer( PurchaseOrder::typeid );

      /* If the XML document has been altered with unknown 
            nodes or attributes, handle them with the 
            UnknownNode and UnknownAttribute events.*/
      serializer->UnknownNode += gcnew XmlNodeEventHandler( this, &Test::serializer_UnknownNode );
      serializer->UnknownAttribute += gcnew XmlAttributeEventHandler( this, &Test::serializer_UnknownAttribute );

      // 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.
      PurchaseOrder^ po;

      /* Use the Deserialize method to restore the object's state with
            data from the XML document. */
      po = dynamic_cast<PurchaseOrder^>(serializer->Deserialize( fs ));

      // Read the order date.
      Console::WriteLine( "OrderDate: {0}", po->OrderDate );

      // Read the shipping address.
      Address^ shipTo = po->ShipTo;
      ReadAddress( shipTo, "Ship To:" );

      // Read the list of ordered items.
      array<OrderedItem^>^items = po->OrderedItems;
      Console::WriteLine( "Items to be shipped:" );
      System::Collections::IEnumerator^ myEnum1 = items->GetEnumerator();
      while ( myEnum1->MoveNext() )
      {
         OrderedItem^ oi = safe_cast<OrderedItem^>(myEnum1->Current);
         Console::WriteLine( "\t{0}\t{1}\t{2}\t{3}\t{4}", oi->ItemName, oi->Description, oi->UnitPrice, oi->Quantity, oi->LineTotal );
      }

      Console::WriteLine( "\t\t\t\t\t Subtotal\t{0}", po->SubTotal );
      Console::WriteLine( "\t\t\t\t\t Shipping\t{0}", po->ShipCost );
      Console::WriteLine( "\t\t\t\t\t Total\t\t{0}", po->TotalCost );
   }

   void ReadAddress( Address^ a, String^ label )
   {
      // Read the fields of the Address object.
      Console::WriteLine( label );
      Console::WriteLine( "\t{0}", a->Name );
      Console::WriteLine( "\t{0}", a->Line1 );
      Console::WriteLine( "\t{0}", a->City );
      Console::WriteLine( "\t{0}", a->State );
      Console::WriteLine( "\t{0}", a->Zip );
      Console::WriteLine();
   }

private:
   void serializer_UnknownNode( Object^ /*sender*/, XmlNodeEventArgs^ e )
   {
      Console::WriteLine( "Unknown Node:{0}\t{1}", e->Name, e->Text );
   }

   void serializer_UnknownAttribute( Object^ /*sender*/, XmlAttributeEventArgs^ e )
   {
      System::Xml::XmlAttribute^ attr = e->Attr;
      Console::WriteLine( "Unknown attribute {0}='{1}'", attr->Name, attr->Value );
   }
};

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

/* The XmlRootAttribute allows you to set an alternate name
   (PurchaseOrder) of the XML element, the element namespace; by
   default, the XmlSerializer uses the class name. The attribute
   also allows you to set the XML namespace for the element.  Lastly,
   the attribute sets the IsNullable property, which specifies whether
   the xsi:null attribute appears if the class instance is set to
   a null reference. */
[XmlRootAttribute("PurchaseOrder", Namespace="http://www.cpandl.com",
IsNullable = false)]
public class PurchaseOrder
{
   public Address ShipTo;
   public string OrderDate;
   /* The XmlArrayAttribute changes the XML element name
    from the default of "OrderedItems" to "Items". */
   [XmlArrayAttribute("Items")]
   public OrderedItem[] OrderedItems;
   public decimal SubTotal;
   public decimal ShipCost;
   public decimal TotalCost;
}

public class Address
{
   /* The XmlAttribute instructs the XmlSerializer to serialize the Name
      field as an XML attribute instead of an XML element (the default
      behavior). */
   [XmlAttribute]
   public string Name;
   public string Line1;

   /* Setting the IsNullable property to false instructs the
      XmlSerializer that the XML attribute will not appear if
      the City field is set to a null reference. */
   [XmlElementAttribute(IsNullable = false)]
   public string City;
   public string State;
   public string Zip;
}

public class OrderedItem
{
   public string ItemName;
   public string Description;
   public decimal UnitPrice;
   public int Quantity;
   public decimal LineTotal;

   /* Calculate is a custom method that calculates the price per item,
      and stores the value in a field. */
   public void Calculate()
   {
      LineTotal = UnitPrice * Quantity;
   }
}

public class Test
{
   public static void Main()
   {
      // Read and write purchase orders.
      Test t = new Test();
      t.CreatePO("po.xml");
      t.ReadPO("po.xml");
   }

   private void CreatePO(string filename)
   {
      // Create an instance of the XmlSerializer class;
      // specify the type of object to serialize.
      XmlSerializer serializer =
      new XmlSerializer(typeof(PurchaseOrder));
      TextWriter writer = new StreamWriter(filename);
      PurchaseOrder po=new PurchaseOrder();

      // Create an address to ship and bill to.
      Address billAddress = new Address();
      billAddress.Name = "Teresa Atkinson";
      billAddress.Line1 = "1 Main St.";
      billAddress.City = "AnyTown";
      billAddress.State = "WA";
      billAddress.Zip = "00000";
      // Set ShipTo and BillTo to the same addressee.
      po.ShipTo = billAddress;
      po.OrderDate = System.DateTime.Now.ToLongDateString();

      // Create an OrderedItem object.
      OrderedItem i1 = new OrderedItem();
      i1.ItemName = "Widget S";
      i1.Description = "Small widget";
      i1.UnitPrice = (decimal) 5.23;
      i1.Quantity = 3;
      i1.Calculate();

      // Insert the item into the array.
      OrderedItem [] items = {i1};
      po.OrderedItems = items;
      // Calculate the total cost.
      decimal subTotal = new decimal();
      foreach(OrderedItem oi in items)
      {
         subTotal += oi.LineTotal;
      }
      po.SubTotal = subTotal;
      po.ShipCost = (decimal) 12.51;
      po.TotalCost = po.SubTotal + po.ShipCost;
      // Serialize the purchase order, and close the TextWriter.
      serializer.Serialize(writer, po);
      writer.Close();
   }

   protected void ReadPO(string filename)
   {
      // Create an instance of the XmlSerializer class;
      // specify the type of object to be deserialized.
      XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder));
      /* If the XML document has been altered with unknown
      nodes or attributes, handle them with the
      UnknownNode and UnknownAttribute events.*/
      serializer.UnknownNode+= new
      XmlNodeEventHandler(serializer_UnknownNode);
      serializer.UnknownAttribute+= new
      XmlAttributeEventHandler(serializer_UnknownAttribute);

      // 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.
      PurchaseOrder po;
      /* Use the Deserialize method to restore the object's state with
      data from the XML document. */
      po = (PurchaseOrder) serializer.Deserialize(fs);
      // Read the order date.
      Console.WriteLine ("OrderDate: " + po.OrderDate);

      // Read the shipping address.
      Address shipTo = po.ShipTo;
      ReadAddress(shipTo, "Ship To:");
      // Read the list of ordered items.
      OrderedItem [] items = po.OrderedItems;
      Console.WriteLine("Items to be shipped:");
      foreach(OrderedItem oi in items)
      {
         Console.WriteLine("\t"+
         oi.ItemName + "\t" +
         oi.Description + "\t" +
         oi.UnitPrice + "\t" +
         oi.Quantity + "\t" +
         oi.LineTotal);
      }
      // Read the subtotal, shipping cost, and total cost.
      Console.WriteLine("\t\t\t\t\t Subtotal\t" + po.SubTotal);
      Console.WriteLine("\t\t\t\t\t Shipping\t" + po.ShipCost);
      Console.WriteLine("\t\t\t\t\t Total\t\t" + po.TotalCost);
   }

   protected void ReadAddress(Address a, string label)
   {
      // Read the fields of the Address object.
      Console.WriteLine(label);
      Console.WriteLine("\t"+ a.Name );
      Console.WriteLine("\t" + a.Line1);
      Console.WriteLine("\t" + a.City);
      Console.WriteLine("\t" + a.State);
      Console.WriteLine("\t" + a.Zip );
      Console.WriteLine();
   }

   private void serializer_UnknownNode
   (object sender, XmlNodeEventArgs e)
   {
      Console.WriteLine("Unknown Node:" +   e.Name + "\t" + e.Text);
   }

   private void serializer_UnknownAttribute
   (object sender, XmlAttributeEventArgs e)
   {
      System.Xml.XmlAttribute attr = e.Attr;
      Console.WriteLine("Unknown attribute " +
      attr.Name + "='" + attr.Value + "'");
   }
}
Imports System.Xml
Imports System.Xml.Serialization
Imports System.IO

' The XmlRootAttribute allows you to set an alternate name
' (PurchaseOrder) of the XML element, the element namespace; by
' default, the XmlSerializer uses the class name. The attribute
' also allows you to set the XML namespace for the element.  Lastly,
' the attribute sets the IsNullable property, which specifies whether
' the xsi:null attribute appears if the class instance is set to
' a null reference. 
<XmlRootAttribute("PurchaseOrder", _
 Namespace := "http://www.cpandl.com", IsNullable := False)> _
Public Class PurchaseOrder
    
    Public ShipTo As Address
    Public OrderDate As String
    ' The XmlArrayAttribute changes the XML element name
    ' from the default of "OrderedItems" to "Items". 
    <XmlArrayAttribute("Items")> _
    Public OrderedItems() As OrderedItem
    Public SubTotal As Decimal
    Public ShipCost As Decimal
    Public TotalCost As Decimal
End Class


Public Class Address
    ' The XmlAttribute instructs the XmlSerializer to serialize the Name
    ' field as an XML attribute instead of an XML element (the default
    ' behavior). 
    <XmlAttribute()> _
    Public Name As String
    Public Line1 As String
    
    ' Setting the IsNullable property to false instructs the
    ' XmlSerializer that the XML attribute will not appear if
    ' the City field is set to a null reference. 
    <XmlElementAttribute(IsNullable := False)> _
    Public City As String
    Public State As String
    Public Zip As String
End Class


Public Class OrderedItem
    Public ItemName As String
    Public Description As String
    Public UnitPrice As Decimal
    Public Quantity As Integer
    Public LineTotal As Decimal
    
    
    ' Calculate is a custom method that calculates the price per item,
    ' and stores the value in a field. 
    Public Sub Calculate()
        LineTotal = UnitPrice * Quantity
    End Sub
End Class


Public Class Test
    
   Public Shared Sub Main()
      ' Read and write purchase orders.
      Dim t As New Test()
      t.CreatePO("po.xml")
      t.ReadPO("po.xml")
   End Sub
    
   Private Sub CreatePO(filename As String)
      ' Create an instance of the XmlSerializer class;
      ' specify the type of object to serialize.
      Dim serializer As New XmlSerializer(GetType(PurchaseOrder))
      Dim writer As New StreamWriter(filename)
      Dim po As New PurchaseOrder()
        
      ' Create an address to ship and bill to.
      Dim billAddress As New Address()
      billAddress.Name = "Teresa Atkinson"
      billAddress.Line1 = "1 Main St."
      billAddress.City = "AnyTown"
      billAddress.State = "WA"
      billAddress.Zip = "00000"
      ' Set ShipTo and BillTo to the same addressee.
      po.ShipTo = billAddress
      po.OrderDate = System.DateTime.Now.ToLongDateString()
        
      ' Create an OrderedItem object.
      Dim i1 As New OrderedItem()
      i1.ItemName = "Widget S"
      i1.Description = "Small widget"
      i1.UnitPrice = CDec(5.23)
      i1.Quantity = 3
      i1.Calculate()
        
      ' Insert the item into the array.
      Dim items(0) As OrderedItem
      items(0) = i1
      po.OrderedItems = items
      ' Calculate the total cost.
      Dim subTotal As New Decimal()
      Dim oi As OrderedItem
      For Each oi In  items
         subTotal += oi.LineTotal
      Next oi
      po.SubTotal = subTotal
      po.ShipCost = CDec(12.51)
      po.TotalCost = po.SubTotal + po.ShipCost
      ' Serialize the purchase order, and close the TextWriter.
      serializer.Serialize(writer, po)
      writer.Close()
   End Sub
    
   Protected Sub ReadPO(filename As String)
      ' Create an instance of the XmlSerializer class;
      ' specify the type of object to be deserialized.
      Dim serializer As New XmlSerializer(GetType(PurchaseOrder))
      ' If the XML document has been altered with unknown
      ' nodes or attributes, handle them with the
      ' UnknownNode and UnknownAttribute events.
      AddHandler serializer.UnknownNode, AddressOf serializer_UnknownNode
      AddHandler serializer.UnknownAttribute, AddressOf serializer_UnknownAttribute
      
      ' 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 po As PurchaseOrder
      ' Use the Deserialize method to restore the object's state with
      ' data from the XML document. 
      po = CType(serializer.Deserialize(fs), PurchaseOrder)
      ' Read the order date.
      Console.WriteLine(("OrderDate: " & po.OrderDate))
        
      ' Read the shipping address.
      Dim shipTo As Address = po.ShipTo
      ReadAddress(shipTo, "Ship To:")
      ' Read the list of ordered items.
      Dim items As OrderedItem() = po.OrderedItems
      Console.WriteLine("Items to be shipped:")
      Dim oi As OrderedItem
      For Each oi In  items
         Console.WriteLine((ControlChars.Tab & oi.ItemName & ControlChars.Tab & _
         oi.Description & ControlChars.Tab & oi.UnitPrice & ControlChars.Tab & _
         oi.Quantity & ControlChars.Tab & oi.LineTotal))
      Next oi
      ' Read the subtotal, shipping cost, and total cost.
      Console.WriteLine(( New String(ControlChars.Tab, 5) & _
      " Subtotal"  & ControlChars.Tab & po.SubTotal))
      Console.WriteLine(New String(ControlChars.Tab, 5) & _
      " Shipping" & ControlChars.Tab & po.ShipCost )
      Console.WriteLine( New String(ControlChars.Tab, 5) & _
      " Total" &  New String(ControlChars.Tab, 2) & po.TotalCost)
    End Sub
    
    Protected Sub ReadAddress(a As Address, label As String)
      ' Read the fields of the Address object.
      Console.WriteLine(label)
      Console.WriteLine(ControlChars.Tab & a.Name)
      Console.WriteLine(ControlChars.Tab & a.Line1)
      Console.WriteLine(ControlChars.Tab & a.City)
      Console.WriteLine(ControlChars.Tab & a.State)
      Console.WriteLine(ControlChars.Tab & a.Zip)
      Console.WriteLine()
    End Sub
        
    Private Sub serializer_UnknownNode(sender As Object, e As XmlNodeEventArgs)
        Console.WriteLine(("Unknown Node:" & e.Name & ControlChars.Tab & e.Text))
    End Sub
    
    
    Private Sub serializer_UnknownAttribute(sender As Object, e As XmlAttributeEventArgs)
        Dim attr As System.Xml.XmlAttribute = e.Attr
        Console.WriteLine(("Unknown attribute " & attr.Name & "='" & attr.Value & "'"))
    End Sub
End Class

설명

XML serialization은 개체의 공용 속성 및 필드를 스토리지 또는 전송을 위한 직렬 형식(이 경우 XML)으로 변환하는 프로세스입니다. 역직렬화는 XML 출력에서 개체를 원래 상태로 다시 만듭니다. serialization은 개체의 상태를 스트림 또는 버퍼에 저장하는 방법으로 생각할 수 있습니다. 예를 들어 ASP.NET 클래스를 XmlSerializer 사용하여 XML 웹 서비스 메시지를 인코딩합니다.

개체의 데이터는 클래스, 필드, 속성, 기본 형식, 배열, 또는 XmlAttribute 개체 형식 XmlElement 의 포함된 XML과 같은 프로그래밍 언어 구문을 사용하여 설명합니다. 고유한 클래스를 만들거나, 특성으로 주석을 추가하거나, Xsd.exe(XML 스키마 정의 도구) 를 사용하여 기존 XSD(XML 스키마 정의) 문서를 기반으로 클래스를 생성할 수 있습니다. XML 스키마가 있는 경우 Xsd.exe 실행하여 스키마에 강력하게 형식화되고 직렬화될 때 스키마를 준수하는 특성으로 주석이 추가된 클래스 집합을 생성할 수 있습니다.

개체와 XML 간에 데이터를 전송하려면 프로그래밍 언어 구문에서 XML 스키마로, XML 스키마에서 프로그래밍 언어 구문으로 매핑해야 합니다. Xsd.exe 같은 및 관련 도구는 XmlSerializer 디자인 타임과 런타임 모두에서 이러한 두 기술 간의 브리지를 제공합니다. 디자인 타임에 Xsd.exe 사용하여 사용자 지정 클래스에서 XML 스키마 문서(.xsd)를 생성하거나 지정된 스키마에서 클래스를 생성합니다. 두 경우 모두 클래스에 사용자 지정 특성이 주석으로 추가되어 XML 스키마 시스템과 공용 언어 런타임 간에 매핑하는 방법을 지시 XmlSerializer 합니다. 런타임에 클래스의 인스턴스를 지정된 스키마 뒤에 있는 XML 문서로 직렬화할 수 있습니다. 마찬가지로 이러한 XML 문서는 런타임 개체로 역직렬화할 수 있습니다. XML 스키마는 선택 사항이며 디자인 타임이나 런타임에는 필요하지 않습니다.

생성된 XML 제어

생성된 XML을 제어하려면 클래스 및 멤버에 특수 특성을 적용할 수 있습니다. 예를 들어 다른 XML 요소 이름을 지정하려면 공용 필드 또는 속성에 를 XmlElementAttribute 적용하고 속성을 설정합니다 ElementName . 유사한 특성의 전체 목록은 XML Serialization을 제어하는 특성을 참조하세요. 인터페이스를 IXmlSerializable 구현하여 XML 출력을 제어할 수도 있습니다.

생성된 XML이 World Wide Consortium 문서 SOAP(Simple Object Access Protocol) 1.1의 섹션 5를 준수해야 하는 경우 를 사용하여 을 XmlTypeMapping생성 XmlSerializer 해야 합니다. 인코딩된 SOAP XML을 추가로 제어하려면 인코딩된 SOAP Serialization을 제어하는 특성에 나열된 특성을 사용합니다.

XmlSerializer 사용하면 강력한 형식의 클래스 작업을 활용할 수 있으며 여전히 XML의 유연성을 가질 수 있습니다. 형식 XmlElementXmlAttribute 의 필드 또는 속성을 사용하거나 XmlNode 강력한 형식의 클래스에서 XML 문서의 일부를 XML 개체로 직접 읽을 수 있습니다.

확장 가능한 XML 스키마를 사용하는 경우 및 XmlAnyAttributeAttribute 특성을 사용하여 XmlAnyElementAttribute 원래 스키마에서 찾을 수 없는 요소 또는 특성을 직렬화하고 역직렬화할 수도 있습니다. 개체를 사용하려면 개체 배열을 반환하는 필드에 를 적용 XmlAnyElementAttribute 하거나 개체 배열 XmlElement 을 반환 XmlAttribute 하는 필드에 를 적용 XmlAnyAttributeAttribute 합니다.

속성 또는 필드가 복합 개체(예: 배열 또는 클래스 인스턴스)를 반환하는 경우 XmlSerializer는 이를 주 XML 문서 내의 중첩된 요소로 변환합니다. 예를 들어 다음 코드의 첫 번째 클래스는 두 번째 클래스의 인스턴스를 반환합니다.

Public Class MyClass  
    Public MyObjectProperty As MyObject  
End Class  

Public Class MyObject  
    Public ObjectName As String  
End Class  
public class MyClass  
{  
    public MyObject MyObjectProperty;  
}  
public class MyObject  
{  
    public string ObjectName;  
}  

직렬화된 XML 출력은 다음과 같습니다.

<MyClass>  
  <MyObjectProperty>  
  <ObjectName>My String</ObjectName>  
  </MyObjectProperty>  
</MyClass>  

스키마에 선택적 요소(minOccurs = '0')가 포함되어 있거나 스키마에 기본값이 포함된 경우 두 가지 옵션이 있습니다. 한 가지 옵션은 다음 코드와 같이 를 사용하여 System.ComponentModel.DefaultValueAttribute 기본값을 지정하는 것입니다.

Public Class PurchaseOrder  
    <System.ComponentModel.DefaultValueAttribute ("2002")> _  
    Public Year As String  
End Class  
public class PurchaseOrder  
{  
    [System.ComponentModel.DefaultValueAttribute ("2002")]  
    public string Year;  
}  

또 다른 옵션은 특수 패턴을 사용하여 에서 인식되는 XmlSerializer부울 필드를 만들고 를 필드에 적용 XmlIgnoreAttribute 하는 것입니다. 패턴은 형식 propertyNameSpecified으로 만들어집니다. 예를 들어 "MyFirstName"이라는 필드가 있는 경우 "MyFirstNameSpecified"라는 필드를 만들어 "MyFirstName"이라는 XML 요소를 생성할지 여부를 지시 XmlSerializer 합니다. 이는 다음 예에서 확인할 수 있습니다.

Public Class OptionalOrder  
    ' This field's value should not be serialized   
    ' if it is uninitialized.  
    Public FirstOrder As String  

    ' Use the XmlIgnoreAttribute to ignore the   
    ' special field named "FirstOrderSpecified".  
    <System.Xml.Serialization.XmlIgnoreAttribute> _  
    Public FirstOrderSpecified As Boolean  
End Class  
public class OptionalOrder  
{  
    // This field should not be serialized   
    // if it is uninitialized.  
    public string FirstOrder;  

    // Use the XmlIgnoreAttribute to ignore the   
    // special field named "FirstOrderSpecified".  
    [System.Xml.Serialization.XmlIgnoreAttribute]  
    public bool FirstOrderSpecified;  
}  

기본 serialization 재정의

적절한 특성 중 하나를 만들고 클래스의 인스턴스에 추가하여 개체 집합과 해당 필드 및 속성 집합의 serialization을 재정의 XmlAttributes 할 수도 있습니다. 용도 이러한 방식으로 serialization을 재정의 합니다: 제어 하 고 원본;에 액세스할 수 없는 경우에 DLL에 있는 개체의 serialization을 보강할 수 먼저 둘째, serializable 클래스의 집합을 만들 수 있지만 여러 가지 방법으로 개체를 직렬화 할. 자세한 내용은 클래스 및 방법: 파생 클래스의 Serialization 제어를 참조 XmlAttributeOverrides 하세요.

개체를 serialize하려면 메서드를 호출합니다 Serialize . 개체를 역직렬화하려면 메서드를 호출합니다 Deserialize .

XML 문서에 XML 네임스페이스를 추가하려면 를 참조하세요 XmlSerializerNamespaces.

참고

XmlSerializer 또는 ICollection를 구현 IEnumerable 하는 클래스에 대해 특별한 처리를 제공합니다. 를 구현하는 클래스는 IEnumerable 단일 매개 변수를 사용하는 public Add 메서드를 구현해야 합니다. 메서드의 매개 변수는 Add 에서 반환된 값의 속성 또는 Current 해당 형식의 기본 중 하나에서 반환 GetEnumerator되는 형식과 동일해야 합니다. 외에도 를 CollectionBaseIEnumerable 구현 ICollection 하는 클래스에는 정수로 사용하는 공용 Item 인덱싱된 속성(C#의 인덱서)이 있어야 하며 형식 정수의 public Count 속성이 있어야 합니다. 메서드에 대한 Add 매개 변수는 속성 또는 Item 해당 형식의 베이스 중 하나에서 반환되는 형식과 동일해야 합니다. 를 구현ICollection하는 클래스의 경우 serialize할 값은 를 호출GetEnumerator하는 것이 아니라 인덱싱된 Item 속성에서 검색됩니다.

개체를 역직렬화하려면 임시 디렉터리(TEMP 환경 변수에 정의된 대로)에 쓸 수 있는 권한이 있어야 합니다.

동적으로 생성된 어셈블리

성능을 높이기 위해 XML serialization 인프라는 지정된 형식을 직렬화하고 역직렬화하는 어셈블리를 동적으로 생성합니다. 인프라는 해당 어셈블리를 찾아 재사용합니다. 이 동작은 다음 생성자를 사용하는 경우에만 발생합니다.

XmlSerializer.XmlSerializer(Type)

XmlSerializer.XmlSerializer(Type, String)

다른 생성자를 사용하는 경우 동일한 어셈블리의 여러 버전이 생성되고 언로드되지 않으므로 메모리 누수 및 성능 저하가 발생합니다. 가장 쉬운 해결 방법은 앞에서 언급한 두 생성자 중 하나를 사용하는 것입니다. 그렇지 않으면 다음 예제와 같이 에서 어셈블리를 Hashtable캐시해야 합니다.

Hashtable serializers = new Hashtable();  

// Use the constructor that takes a type and XmlRootAttribute.  
XmlSerializer s = new XmlSerializer(typeof(MyClass), myRoot);  

// Implement a method named GenerateKey that creates unique keys   
// for each instance of the XmlSerializer. The code should take   
// into account all parameters passed to the XmlSerializer   
// constructor.  
object key = GenerateKey(typeof(MyClass), myRoot);  

// Check the local cache for a matching serializer.  
XmlSerializer ser = (XmlSerializer)serializers[key];  
if (ser == null)   
{  
    ser = new XmlSerializer(typeof(MyClass), myRoot);  
    // Cache the serializer.  
    serializers[key] = ser;  
}

// Use the serializer to serialize or deserialize.
Dim serializers As New Hashtable()  

' Use the constructor that takes a type and XmlRootAttribute.  
Dim s As New XmlSerializer(GetType([MyClass]), myRoot)  

' Implement a method named GenerateKey that creates unique keys   
' for each instance of the XmlSerializer. The code should take   
' into account all parameters passed to the XmlSerializer   
' constructor.  
Dim key As Object = GenerateKey(GetType([MyClass]), myRoot)  

' Check the local cache for a matching serializer.  
Dim ser As XmlSerializer = CType(serializers(key), XmlSerializer)  

If ser Is Nothing Then  
    ser = New XmlSerializer(GetType([MyClass]), myRoot)  
    ' Cache the serializer.  
    serializers(key) = ser  
End If  

' Use the serializer to serialize or deserialize.

ArrayList 및 제네릭 목록의 serialization

XmlSerializer 다음을 직렬화하거나 역직렬화할 수 없습니다.

부호 없는 Long 열거형의 직렬화

XmlSerializer 다음 조건이 true이면 를 인스턴스화하여 열거형을 serialize할 수 없습니다. 열거형은 unsigned long 형식입니다(ulongC#의 경우). 열거형에는 값이 9,223,372,036,854,775,807보다 큰 멤버가 포함됩니다. 예를 들어 다음을 serialize할 수 없습니다.

public enum LargeNumbers: ulong  
{  
    a = 9223372036854775808  
}  
// At runtime, the following code will fail.  
xmlSerializer mySerializer=new XmlSerializer(typeof(LargeNumbers));  

사용되지 않는 특성으로 표시된 개체가 더 이상 직렬화되지 않음

.NET Framework 3.5부터 클래스는 XmlSerializer 더 이상 로 [Obsolete]표시된 개체를 serialize하지 않습니다.

생성자

XmlSerializer()

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

XmlSerializer(Type)

지정된 형식의 개체를 XML 문서로 직렬화하고 XML 문서를 지정된 형식의 개체로 역직렬화할 수 있는 XmlSerializer 클래스의 새 인스턴스를 초기화합니다.

XmlSerializer(Type, String)

지정된 형식의 개체를 XML 문서로 직렬화하고 XML 문서를 지정된 형식의 개체로 역직렬화할 수 있는 XmlSerializer 클래스의 새 인스턴스를 초기화합니다. 모든 XML 요소의 기본 네임스페이스를 지정합니다.

XmlSerializer(Type, Type[])

지정된 형식의 개체를 XML 문서로 직렬화하고 XML 문서를 지정된 형식의 개체로 역직렬화할 수 있는 XmlSerializer 클래스의 새 인스턴스를 초기화합니다. 필드 또는 속성이 배열을 반환하는 경우 extraTypes 매개 변수는 배열에 삽입될 수 있는 개체를 지정합니다.

XmlSerializer(Type, XmlAttributeOverrides)

지정된 형식의 개체를 XML 문서로 직렬화하고 XML 문서를 지정된 형식의 개체로 역직렬화할 수 있는 XmlSerializer 클래스의 새 인스턴스를 초기화합니다. serialize되는 각 개체는 클래스의 인스턴스를 포함할 수 있으며, 이 오버로드는 다른 클래스로 재정의할 수 있습니다.

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

XmlSerializer 형식의 개체를 XML 문서 인스턴스로 직렬화하고 XML 문서 인스턴스를 Object 형식의 개체로 역직렬화할 수 있는 Object 클래스의 새 인스턴스를 초기화합니다. serialize되는 각 개체는 클래스의 인스턴스를 포함할 수 있으며, 이 오버로드에서 그 클래스를 다른 클래스로 재정의합니다. 또한 이 오버로드는 모든 XML 요소의 기본 네임스페이스 및 XML 루트 요소로 사용할 클래스를 지정합니다.

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

XmlSerializer 형식의 개체를 XML 문서 인스턴스로 직렬화하고 XML 문서 인스턴스를 Object 형식의 개체로 역직렬화할 수 있는 Object 클래스의 새 인스턴스를 초기화합니다. serialize되는 각 개체는 클래스의 인스턴스를 포함할 수 있으며, 이 오버로드에서 그 클래스를 다른 클래스로 재정의합니다. 또한 이 오버로드는 모든 XML 요소의 기본 네임스페이스 및 XML 루트 요소로 사용할 클래스를 지정합니다.

XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String, Evidence)
사용되지 않습니다.

지정된 형식의 개체를 XML 문서 인스턴스로 직렬화하고 XML 문서 인스턴스를 지정된 형식의 개체로 역직렬화할 수 있는 XmlSerializer 클래스의 새 인스턴스를 초기화합니다. 이 오버로드를 통해 serialization 또는 deserialization 작업 동안 발생할 수 있는 다른 형식뿐 아니라 모든 XML 요소에 대한 기본 네임스페이스, XML 루트 요소로 사용할 클래스, 클래스의 위치 및 액세스하는 데 필요한 자격 증명을 제공할 수 있습니다.

XmlSerializer(Type, XmlRootAttribute)

지정된 형식의 개체를 XML 문서로 직렬화하고 XML 문서를 지정된 형식의 개체로 역직렬화할 수 있는 XmlSerializer 클래스의 새 인스턴스를 초기화합니다. 또한 XML 루트 요소로 사용할 클래스를 지정합니다.

XmlSerializer(XmlTypeMapping)

특정 형식을 다른 형식에 매핑하는 개체를 사용하여 XmlSerializer 클래스의 인스턴스를 초기화합니다.

메서드

CanDeserialize(XmlReader)

XmlSerializer가 지정된 XML 문서를 역직렬화할 수 있는지 여부를 나타내는 값을 가져옵니다.

CreateReader()

serialize할 XML 문서를 읽는 데 사용되는 개체를 반환합니다.

CreateWriter()

파생 클래스에서 재정의되는 경우 개체를 serialize하는 데 사용되는 작성기를 반환합니다.

Deserialize(Stream)

지정된 Stream에 포함된 XML 문서를 역직렬화합니다.

Deserialize(TextReader)

지정된 TextReader에 포함된 XML 문서를 역직렬화합니다.

Deserialize(XmlReader)

지정된 XmlReader에 포함된 XML 문서를 역직렬화합니다.

Deserialize(XmlReader, String)

지정된 XmlReader에 포함된 XML 문서와 인코딩 스타일을 역직렬화합니다.

Deserialize(XmlReader, String, XmlDeserializationEvents)

지정된 XmlReader에 포함된 데이터를 사용하여 개체를 역직렬화합니다.

Deserialize(XmlReader, XmlDeserializationEvents)

지정된 XmlReader에 포함된 XML 문서를 역직렬화하고 deserialization을 수행하는 동안 발생하는 이벤트를 재정의할 수 있도록 합니다.

Deserialize(XmlSerializationReader)

지정된 XmlSerializationReader에 포함된 XML 문서를 역직렬화합니다.

Equals(Object)

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

(다음에서 상속됨 Object)
FromMappings(XmlMapping[])

XmlSerializer 개체의 배열에서 만들어진 XmlTypeMapping 개체의 배열을 반환합니다.

FromMappings(XmlMapping[], Evidence)
사용되지 않습니다.

XML 형식 간의 매핑에 따라 생성되는 XmlSerializer 클래스의 인스턴스를 반환합니다.

FromMappings(XmlMapping[], Type)

지정된 매핑에 따라 XmlSerializer 클래스의 인스턴스를 반환합니다.

FromTypes(Type[])

형식 배열에서 만든 XmlSerializer 개체의 배열을 반환합니다.

GenerateSerializer(Type[], XmlMapping[])

지정된 매핑을 사용하여 하나 이상의 지정된 형식을 직렬화 또는 역직렬화하는 데 사용되는 사용자 지정 직렬 변환기가 포함된 어셈블리를 반환합니다.

GenerateSerializer(Type[], XmlMapping[], CompilerParameters)

지정된 매핑과 컴파일러 설정 및 옵션을 사용하여 하나 이상의 지정된 형식을 직렬화 또는 역직렬화하는 데 사용되는 사용자 지정 직렬 변환기가 포함된 어셈블리를 반환합니다.

GetHashCode()

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

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

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

(다음에서 상속됨 Object)
GetXmlSerializerAssemblyName(Type)

지정된 형식을 직렬화 또는 역직렬화하기 위해 특별히 생성된 하나 또는 여러 버전의 XmlSerializer가 포함된 어셈블리의 이름을 반환합니다.

GetXmlSerializerAssemblyName(Type, String)

지정된 네임스페이스의 지정된 형식에 대한 serializer가 포함된 어셈블리의 이름을 반환합니다.

MemberwiseClone()

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

(다음에서 상속됨 Object)
Serialize(Object, XmlSerializationWriter)

지정된 Object를 serialize하고 지정된 XmlSerializationWriter을 사용하여 XML 문서를 파일에 씁니다.

Serialize(Stream, Object)

지정된 Object를 serialize하고 지정된 Stream을 사용하여 XML 문서를 파일에 씁니다.

Serialize(Stream, Object, XmlSerializerNamespaces)

지정된 Object를 serialize하고 지정된 네임스페이스를 참조하는 지정된 Stream을 사용하여 XML 문서를 파일에 씁니다.

Serialize(TextWriter, Object)

지정된 Object를 serialize하고 지정된 TextWriter을 사용하여 XML 문서를 파일에 씁니다.

Serialize(TextWriter, Object, XmlSerializerNamespaces)

지정된 Object를 serialize하고 지정된 TextWriter를 사용하여 XML 문서를 파일에 쓰며 지정된 네임스페이스를 참조합니다.

Serialize(XmlWriter, Object)

지정된 Object를 serialize하고 지정된 XmlWriter을 사용하여 XML 문서를 파일에 씁니다.

Serialize(XmlWriter, Object, XmlSerializerNamespaces)

지정된 Object를 serialize하고 지정된 XmlWriter를 사용하여 XML 문서를 파일에 쓰며 지정된 네임스페이스를 참조합니다.

Serialize(XmlWriter, Object, XmlSerializerNamespaces, String)

지정된 개체를 serialize하고 지정된 XmlWriter를 사용하여 XML 문서를 파일에 쓰며 지정된 네임스페이스 및 인코딩 스타일을 참조합니다.

Serialize(XmlWriter, Object, XmlSerializerNamespaces, String, String)

지정된 Object를 serialize하고 지정된 XmlWriter, XML 네임스페이스 및 인코딩을 사용하여 XML 문서를 파일에 씁니다.

ToString()

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

(다음에서 상속됨 Object)

이벤트

UnknownAttribute

XmlSerializer가 deserialization을 수행하는 동안 알 수 없는 형식의 XML 특성이 나타날 때 발생합니다.

UnknownElement

XmlSerializer가 deserialization을 수행하는 동안 알 수 없는 형식의 XML 요소를 발견하면 발생합니다.

UnknownNode

XmlSerializer가 deserialization을 수행하는 동안 알 수 없는 형식의 XML 노드가 나타날 때 발생합니다.

UnreferencedObject

SOAP로 인코딩된 XML 스트림의 deserialization을 수행하는 동안 XmlSerializer가 사용되지 않았거나 참조되지 않은 인식할 수 있는 형식을 발견하면 발생합니다.

적용 대상

스레드 보안

이 형식은 스레드로부터 안전합니다.

추가 정보