XmlSerializer.Serialize 메서드

정의

개체를 XML 문서로 serialize합니다.Serializes an object into an XML document.

오버로드

Serialize(XmlWriter, Object)

지정된 Object를 serialize하고 지정된 XmlWriter을 사용하여 XML 문서를 파일에 씁니다.Serializes the specified Object and writes the XML document to a file using the specified XmlWriter.

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

지정된 Object를 serialize하고 지정된 XmlWriter, XML 네임스페이스 및 인코딩을 사용하여 XML 문서를 파일에 씁니다.Serializes the specified Object and writes the XML document to a file using the specified XmlWriter, XML namespaces, and encoding.

Serialize(XmlWriter, Object, XmlSerializerNamespaces, String)

지정된 개체를 serialize하고 지정된 XmlWriter를 사용하여 XML 문서를 파일에 쓰며 지정된 네임스페이스 및 인코딩 스타일을 참조합니다.Serializes the specified object and writes the XML document to a file using the specified XmlWriter and references the specified namespaces and encoding style.

Serialize(XmlWriter, Object, XmlSerializerNamespaces)

지정된 Object를 serialize하고 지정된 XmlWriter를 사용하여 XML 문서를 파일에 쓰며 지정된 네임스페이스를 참조합니다.Serializes the specified Object and writes the XML document to a file using the specified XmlWriter and references the specified namespaces.

Serialize(TextWriter, Object, XmlSerializerNamespaces)

지정된 Object를 serialize하고 지정된 TextWriter를 사용하여 XML 문서를 파일에 쓰며 지정된 네임스페이스를 참조합니다.Serializes the specified Object and writes the XML document to a file using the specified TextWriter and references the specified namespaces.

Serialize(Object, XmlSerializationWriter)

지정된 Object를 serialize하고 지정된 XmlSerializationWriter을 사용하여 XML 문서를 파일에 씁니다.Serializes the specified Object and writes the XML document to a file using the specified XmlSerializationWriter.

Serialize(TextWriter, Object)

지정된 Object를 serialize하고 지정된 TextWriter을 사용하여 XML 문서를 파일에 씁니다.Serializes the specified Object and writes the XML document to a file using the specified TextWriter.

Serialize(Stream, Object)

지정된 Object를 serialize하고 지정된 Stream을 사용하여 XML 문서를 파일에 씁니다.Serializes the specified Object and writes the XML document to a file using the specified Stream.

Serialize(Stream, Object, XmlSerializerNamespaces)

지정된 Object를 serialize하고 지정된 네임스페이스를 참조하는 지정된 Stream을 사용하여 XML 문서를 파일에 씁니다.Serializes the specified Object and writes the XML document to a file using the specified Stream that references the specified namespaces.

Serialize(XmlWriter, Object)

지정된 Object를 serialize하고 지정된 XmlWriter을 사용하여 XML 문서를 파일에 씁니다.Serializes the specified Object and writes the XML document to a file using the specified XmlWriter.

public:
 void Serialize(System::Xml::XmlWriter ^ xmlWriter, System::Object ^ o);
public void Serialize (System.Xml.XmlWriter xmlWriter, object o);
member this.Serialize : System.Xml.XmlWriter * obj -> unit
Public Sub Serialize (xmlWriter As XmlWriter, o As Object)

매개 변수

xmlWriter
XmlWriter

XML 문서를 쓰는 데 사용되는 XmlWriter입니다.The XmlWriter used to write the XML document.

o
Object

serialize할 Object입니다.The Object to serialize.

예외

serialization 중 오류가 발생했습니다.An error occurred during serialization. InnerException 속성을 사용하여 원래 예외를 사용할 수 있습니다.The original exception is available using the InnerException property.

예제

다음 예제에서는를 사용 하 여 개체를 serialize 합니다 XmlWriter .The following example serializes an object using an XmlWriter.

#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;

// This is the class that will be serialized.
public ref class OrderedItem
{
public:
   String^ ItemName;
   String^ Description;
   Decimal UnitPrice;
   int Quantity;
   Decimal LineTotal;

   // A custom method used to calculate price per item.
   void Calculate()
   {
      LineTotal = UnitPrice * Quantity;
   }
};

void SerializeObject( String^ filename )
{
   Console::WriteLine( "Writing With XmlTextWriter" );
   XmlSerializer^ serializer = gcnew XmlSerializer( OrderedItem::typeid );
   OrderedItem^ i = gcnew OrderedItem;
   i->ItemName = "Widget";
   i->Description = "Regular Widget";
   i->Quantity = 10;
   i->UnitPrice = (Decimal)2.30;
   i->Calculate();

   // Create an XmlTextWriter using a FileStream.
   Stream^ fs = gcnew FileStream( filename,FileMode::Create );
   XmlWriter^ writer = gcnew XmlTextWriter( fs,Encoding::Unicode );

   // Serialize using the XmlTextWriter.
   serializer->Serialize( writer, i );
   writer->Close();
}

int main()
{
   // Write a purchase order.
   SerializeObject( "simple.xml" );
}
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

// This is the class that will be serialized.
public class OrderedItem
{
   public string ItemName;
   public string Description;
   public decimal UnitPrice;
   public int Quantity;
   public decimal LineTotal;
   // A custom method used to calculate price per item.
   public void Calculate()
   {
      LineTotal = UnitPrice * Quantity;
   }
}

public class Test{
   public static void Main()
   {
      Test t = new Test();
      // Write a purchase order.
      t.SerializeObject("simple.xml");
   }

   private void SerializeObject(string filename)
   {
      Console.WriteLine("Writing With XmlTextWriter");

      XmlSerializer serializer =
      new XmlSerializer(typeof(OrderedItem));
      OrderedItem i = new OrderedItem();
      i.ItemName = "Widget";
      i.Description = "Regular Widget";
      i.Quantity = 10;
      i.UnitPrice = (decimal) 2.30;
      i.Calculate();
      // Create an XmlTextWriter using a FileStream.
      Stream fs = new FileStream(filename, FileMode.Create);
      XmlWriter writer =
      new XmlTextWriter(fs, Encoding.Unicode);
      // Serialize using the XmlTextWriter.
      serializer.Serialize(writer, i);
      writer.Close();
   }
}

Imports System.IO
Imports System.Text
Imports System.Xml
Imports System.Xml.Serialization


' 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
    Public LineTotal As Decimal
    
    ' A custom method used to calculate price per item.
    Public Sub Calculate()
        LineTotal = UnitPrice * Quantity
    End Sub
End Class


Public Class Test
    
    Public Shared Sub Main()
        Dim t As New Test()
        ' Write a purchase order.
        t.SerializeObject("simple.xml")
    End Sub
        
    Private Sub SerializeObject(ByVal filename As String)
        Console.WriteLine("Writing With XmlTextWriter")
        
        Dim serializer As New XmlSerializer(GetType(OrderedItem))
        Dim i As New OrderedItem()
        With i
            .ItemName = "Widget"
            .Description = "Regular Widget"
            .Quantity = 10
            .UnitPrice = CDec(2.3)
            .Calculate()
        End With
        ' Create an XmlTextWriter using a FileStream.
        Dim fs As New FileStream(filename, FileMode.Create)
        Dim writer As New XmlTextWriter(fs, Encoding.Unicode)
        ' Serialize using the XmlTextWriter.
        serializer.Serialize(writer, i)
        writer.Close()
    End Sub
End Class

<?xml version="1.0"?>
 <OrderedItem xmlns:inventory="http://www.cpandl.com" xmlns:money="http://www.cohowinery.com">
   <inventory:ItemName>Widget</inventory:ItemName>
   <inventory:Description>Regular Widget</inventory:Description>
   <money:UnitPrice>2.3</money:UnitPrice>
   <inventory:Quantity>10</inventory:Quantity>
   <money:LineTotal>23</money:LineTotal>
 </OrderedItem>

설명

Serialize메서드는 개체의 공용 필드 및 읽기/쓰기 속성을 XML로 변환 합니다.The Serialize method converts the public fields and read/write properties of an object into XML. 메서드, 인덱서, 전용 필드 또는 읽기 전용 속성을 변환 하지 않습니다.It does not convert methods, indexers, private fields, or read-only properties. Public 및 private의 모든 개체의 필드와 속성을 serialize 하려면를 사용 BinaryFormatter 합니다.To serialize all an object's fields and properties, both public and private, use the BinaryFormatter.

xmlWriter매개 변수에서 추상 클래스에서 파생 되는 개체를 지정 XmlWriter 합니다.In the xmlWriter parameter, specify an object that derives from the abstract XmlWriter class. XmlTextWriter 에서 파생 XmlWriter 됩니다.The XmlTextWriter derives from the XmlWriter.

참고

는의 배열과 배열의 배열을 XmlSerializer serialize 할 수 없습니다. ArrayList List<T>The XmlSerializer cannot serialize the following: arrays of ArrayList and arrays of List<T>.

추가 정보

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

지정된 Object를 serialize하고 지정된 XmlWriter, XML 네임스페이스 및 인코딩을 사용하여 XML 문서를 파일에 씁니다.Serializes the specified Object and writes the XML document to a file using the specified XmlWriter, XML namespaces, and encoding.

public:
 void Serialize(System::Xml::XmlWriter ^ xmlWriter, System::Object ^ o, System::Xml::Serialization::XmlSerializerNamespaces ^ namespaces, System::String ^ encodingStyle, System::String ^ id);
public void Serialize (System.Xml.XmlWriter xmlWriter, object o, System.Xml.Serialization.XmlSerializerNamespaces namespaces, string encodingStyle, string id);
member this.Serialize : System.Xml.XmlWriter * obj * System.Xml.Serialization.XmlSerializerNamespaces * string * string -> unit
Public Sub Serialize (xmlWriter As XmlWriter, o As Object, namespaces As XmlSerializerNamespaces, encodingStyle As String, id As String)

매개 변수

xmlWriter
XmlWriter

XML 문서를 쓰는 데 사용되는 XmlWriter입니다.The XmlWriter used to write the XML document.

o
Object

serialize할 개체입니다.The object to serialize.

namespaces
XmlSerializerNamespaces

사용할 네임스페이스 및 접두사가 포함된 XmlSerializerNamespaces의 인스턴스입니다.An instance of the XmlSerializerNamespaces that contains namespaces and prefixes to use.

encodingStyle
String

문서에서 사용되는 인코딩입니다.The encoding used in the document.

id
String

SOAP로 인코딩된 메시지의 경우 id 특성을 생성하는 데 사용되는 기본 문자열입니다.For SOAP encoded messages, the base used to generate id attributes.

설명

Id 매개 변수는 SOAP id를 만드는 데 사용 되는 기본 문자열을 제공 합니다.The id parameter supplies the base string used to create SOAP ids. 기본적으로 "id1", "id2" 등이 있습니다.By default, these are "id1", "id2" and so on. 그러나 매개 변수가 "myBase"로 설정 된 경우 생성 되는 값은 "myBaseid1", "myBaseid2" 등입니다.But if the parameter is set to "myBase" the generated values are "myBaseid1", "myBaseid2" and so on. 이 기능은 전체 SOAP 메시지에서 고유한 id 값을 만드는 데 사용 됩니다.This functionality is used to create unique id values across the whole SOAP message.

Serialize(XmlWriter, Object, XmlSerializerNamespaces, String)

지정된 개체를 serialize하고 지정된 XmlWriter를 사용하여 XML 문서를 파일에 쓰며 지정된 네임스페이스 및 인코딩 스타일을 참조합니다.Serializes the specified object and writes the XML document to a file using the specified XmlWriter and references the specified namespaces and encoding style.

public:
 void Serialize(System::Xml::XmlWriter ^ xmlWriter, System::Object ^ o, System::Xml::Serialization::XmlSerializerNamespaces ^ namespaces, System::String ^ encodingStyle);
public void Serialize (System.Xml.XmlWriter xmlWriter, object o, System.Xml.Serialization.XmlSerializerNamespaces namespaces, string encodingStyle);
member this.Serialize : System.Xml.XmlWriter * obj * System.Xml.Serialization.XmlSerializerNamespaces * string -> unit
Public Sub Serialize (xmlWriter As XmlWriter, o As Object, namespaces As XmlSerializerNamespaces, encodingStyle As String)

매개 변수

xmlWriter
XmlWriter

XML 문서를 쓰는 데 사용되는 XmlWriter입니다.The XmlWriter used to write the XML document.

o
Object

serialize할 개체입니다.The object to serialize.

namespaces
XmlSerializerNamespaces

개체에서 참조하는 XmlSerializerNamespaces입니다.The XmlSerializerNamespaces referenced by the object.

encodingStyle
String

serialize된 XML의 인코딩 스타일입니다.The encoding style of the serialized XML.

예외

serialization 중 오류가 발생했습니다.An error occurred during serialization. InnerException 속성을 사용하여 원래 예외를 사용할 수 있습니다.The original exception is available using the InnerException property.

설명

Serialize메서드가 호출 되 면 개체의 공용 필드 및 읽기/쓰기 속성이 XML로 변환 됩니다.When the Serialize method is invoked, the public fields and read/write properties of an object are converted into XML. 메서드, 인덱서, 전용 필드 및 읽기 전용 속성은 serialize 되지 않습니다.Methods, indexers, private fields, and read-only properties are not serialized. Public 및 private의 모든 필드와 속성을 serialize 하려면를 사용 BinaryFormatter 합니다.To serialize all fields and properties, both public and private, use the BinaryFormatter.

xmlWriterXML 문서를 작성 하도록 디자인 된 추상 클래스에서 파생 되는 개체를 지정 하려면 매개 변수를 사용 XmlWriter 합니다.Use the xmlWriter parameter to specify an object that derives from the abstract XmlWriter class, which is designed to write XML documents. XmlTextWriter 에서 파생 XmlWriter 됩니다.The XmlTextWriter derives from the XmlWriter.

encodingStyleSoap 버전 1.1 인코딩에 대해 매개 변수를 ""로 설정 하 http://schemas.xmlsoap.org/soap/encoding/ 고, 그렇지 않으면 http://www.w3.org/2001/12/soap-encoding soap 버전 1.2 인코딩에 대해 ""로 설정 합니다.Set the encodingStyle parameter to "http://schemas.xmlsoap.org/soap/encoding/" for SOAP version 1.1 encoding; otherwise, set it to "http://www.w3.org/2001/12/soap-encoding" for SOAP version 1.2 encoding.

참고

는의 배열과 배열의 배열을 XmlSerializer serialize 할 수 없습니다. ArrayList List<T>The XmlSerializer cannot serialize the following: arrays of ArrayList and arrays of List<T>.

추가 정보

Serialize(XmlWriter, Object, XmlSerializerNamespaces)

지정된 Object를 serialize하고 지정된 XmlWriter를 사용하여 XML 문서를 파일에 쓰며 지정된 네임스페이스를 참조합니다.Serializes the specified Object and writes the XML document to a file using the specified XmlWriter and references the specified namespaces.

public:
 void Serialize(System::Xml::XmlWriter ^ xmlWriter, System::Object ^ o, System::Xml::Serialization::XmlSerializerNamespaces ^ namespaces);
public void Serialize (System.Xml.XmlWriter xmlWriter, object o, System.Xml.Serialization.XmlSerializerNamespaces namespaces);
member this.Serialize : System.Xml.XmlWriter * obj * System.Xml.Serialization.XmlSerializerNamespaces -> unit
Public Sub Serialize (xmlWriter As XmlWriter, o As Object, namespaces As XmlSerializerNamespaces)

매개 변수

xmlWriter
XmlWriter

XML 문서를 쓰는 데 사용되는 XmlWriter입니다.The XmlWriter used to write the XML document.

o
Object

serialize할 Object입니다.The Object to serialize.

namespaces
XmlSerializerNamespaces

개체에서 참조하는 XmlSerializerNamespaces입니다.The XmlSerializerNamespaces referenced by the object.

예외

serialization 중 오류가 발생했습니다.An error occurred during serialization. InnerException 속성을 사용하여 원래 예외를 사용할 수 있습니다.The original exception is available using the InnerException property.

예제

다음 예제에서는를 사용 하 여 개체를 serialize 합니다 XmlWriter .The following example serializes an object with an XmlWriter. 또한이 예제에서는를 만들고 XmlSerializerNamespaces 두 개의 네임 스페이스를 개체에 추가 합니다.The example also creates an XmlSerializerNamespaces and adds two namespaces to the object. 클래스의 여러 인스턴스는 XmlElementAttribute 클래스 멤버에 적용 되어 각 요소에 대 한 네임 스페이스를 지정 합니다.Several instances of the XmlElementAttribute class are applied to the class members to specify the namespace for each element.

#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;

// This is the class that will be serialized.
public ref class OrderedItem
{
public:

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

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

   [XmlElement(Namespace="http://www.cohowinery.com")]
   Decimal UnitPrice;

   [XmlElement(Namespace="http://www.cpandl.com")]
   int Quantity;

   [XmlElement(Namespace="http://www.cohowinery.com")]
   Decimal LineTotal;

   // A custom method used to calculate price per item.
   void Calculate()
   {
      LineTotal = UnitPrice * Quantity;
   }
};

void SerializeObject( String^ filename )
{
   Console::WriteLine( "Writing With XmlTextWriter" );
   XmlSerializer^ serializer = gcnew XmlSerializer( OrderedItem::typeid );
   OrderedItem^ i = gcnew OrderedItem;
   i->ItemName = "Widget";
   i->Description = "Regular Widget";
   i->Quantity = 10;
   i->UnitPrice = (Decimal)2.30;
   i->Calculate();

   // Create an XmlSerializerNamespaces object.
   XmlSerializerNamespaces^ ns = gcnew XmlSerializerNamespaces;

   // Add two namespaces with prefixes.
   ns->Add( "inventory", "http://www.cpandl.com" );
   ns->Add( "money", "http://www.cohowinery.com" );

   // Create an XmlTextWriter using a FileStream.
   Stream^ fs = gcnew FileStream( filename,FileMode::Create );
   XmlWriter^ writer = gcnew XmlTextWriter( fs,gcnew UTF8Encoding );

   // Serialize using the XmlTextWriter.
   serializer->Serialize( writer, i, ns );
   writer->Close();
}

int main()
{
   // Write a purchase order.
   SerializeObject( "simple.xml" );
}
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

// This is the class that will be serialized.
public class OrderedItem
{
   [XmlElement(Namespace = "http://www.cpandl.com")]
   public string ItemName;
   [XmlElement(Namespace = "http://www.cpandl.com")]
   public string Description;
   [XmlElement(Namespace="http://www.cohowinery.com")]
   public decimal UnitPrice;
   [XmlElement(Namespace = "http://www.cpandl.com")]
   public int Quantity;
   [XmlElement(Namespace="http://www.cohowinery.com")]
   public decimal LineTotal;
   // A custom method used to calculate price per item.
   public void Calculate()
   {
      LineTotal = UnitPrice * Quantity;
   }
}

public class Test{
   public static void Main()
   {
      Test t = new Test();
   // Write a purchase order.
   t.SerializeObject("simple.xml");
   }

   private void SerializeObject(string filename)
   {
      Console.WriteLine("Writing With XmlTextWriter");

      XmlSerializer serializer =
      new XmlSerializer(typeof(OrderedItem));
      OrderedItem i = new OrderedItem();
      i.ItemName = "Widget";
      i.Description = "Regular Widget";
      i.Quantity = 10;
      i.UnitPrice = (decimal) 2.30;
      i.Calculate();

      // Create an XmlSerializerNamespaces object.
      XmlSerializerNamespaces ns =
      new XmlSerializerNamespaces();
      // Add two namespaces with prefixes.
      ns.Add("inventory", "http://www.cpandl.com");
      ns.Add("money", "http://www.cohowinery.com");
      // Create an XmlTextWriter using a FileStream.
      Stream fs = new FileStream(filename, FileMode.Create);
      XmlWriter writer =
      new XmlTextWriter(fs, new UTF8Encoding());
      // Serialize using the XmlTextWriter.
      serializer.Serialize(writer, i, ns);
      writer.Close();
   }
}

Imports System.IO
Imports System.Text
Imports System.Xml
Imports System.Xml.Serialization


' This is the class that will be serialized.
Public Class OrderedItem
    <XmlElement(Namespace := "http://www.cpandl.com")> _
    Public ItemName As String
    
    <XmlElement(Namespace := "http://www.cpandl.com")> _
    Public Description As String
    
    <XmlElement(Namespace := "http://www.cohowinery.com")> _
    Public UnitPrice As Decimal
    
    <XmlElement(Namespace := "http://www.cpandl.com")> _
    Public Quantity As Integer
    
    <XmlElement(Namespace := "http://www.cohowinery.com")> _
    Public LineTotal As Decimal
    
    'A custom method used to calculate price per item.
    Public Sub Calculate()
        LineTotal = UnitPrice * Quantity
    End Sub
End Class


Public Class Test
    
    Public Shared Sub Main()
        Dim t As New Test()
        ' Write a purchase order.
        t.SerializeObject("simple.xml")
    End Sub    
    
    Private Sub SerializeObject(ByVal filename As String)
        Console.WriteLine("Writing With XmlTextWriter")
        
        Dim serializer As New XmlSerializer(GetType(OrderedItem))
        Dim i As New OrderedItem()
        With i
            .ItemName = "Widget"
            .Description = "Regular Widget"
            .Quantity = 10
            .UnitPrice = CDec(2.3)
            .Calculate()
        End With
        
        ' Create an XmlSerializerNamespaces object.
        Dim ns As New XmlSerializerNamespaces()
        ' Add two namespaces with prefixes.
        ns.Add("inventory", "http://www.cpandl.com")
        ns.Add("money", "http://www.cohowinery.com")
        ' Create an XmlTextWriter using a FileStream.
        Dim fs As New FileStream(filename, FileMode.Create)
        Dim writer As New XmlTextWriter(fs, New UTF8Encoding())
        ' Serialize using the XmlTextWriter.
        serializer.Serialize(writer, i, ns)
        writer.Close()
    End Sub
End Class

<?xml version="1.0"?>
 <OrderedItem xmlns:inventory="http://www.cpandl.com" xmlns:money="http://www.cohowinery.com">
   <inventory:ItemName>Widget</inventory:ItemName>
   <inventory:Description>Regular Widget</inventory:Description>
   <money:UnitPrice>2.3</money:UnitPrice>
   <inventory:Quantity>10</inventory:Quantity>
   <money:LineTotal>23</money:LineTotal>
 </OrderedItem>

설명

Serialize메서드가 호출 되 면 개체의 공용 필드 및 읽기/쓰기 속성이 XML로 변환 됩니다.When the Serialize method is invoked, the public fields and read/write properties of an object are converted into XML. 메서드, 인덱서, 전용 필드 및 읽기 전용 속성은 serialize 되지 않습니다.Methods, indexers, private fields, and read-only properties are not serialized. Public 및 private의 모든 필드와 속성을 serialize 하려면를 사용 BinaryFormatter 합니다.To serialize all fields and properties, both public and private, use the BinaryFormatter.

xmlWriterXML 문서를 작성 하도록 디자인 된 추상 클래스에서 파생 되는 개체를 지정 하려면 매개 변수를 사용 XmlWriter 합니다.Use the xmlWriter parameter to specify an object that derives from the abstract XmlWriter class, which is designed to write XML documents. XmlTextWriter 에서 파생 XmlWriter 됩니다.The XmlTextWriter derives from the XmlWriter.

참고

는의 배열과 배열의 배열을 XmlSerializer serialize 할 수 없습니다. ArrayList List<T>The XmlSerializer cannot serialize the following: arrays of ArrayList and arrays of List<T>.

추가 정보

Serialize(TextWriter, Object, XmlSerializerNamespaces)

지정된 Object를 serialize하고 지정된 TextWriter를 사용하여 XML 문서를 파일에 쓰며 지정된 네임스페이스를 참조합니다.Serializes the specified Object and writes the XML document to a file using the specified TextWriter and references the specified namespaces.

public:
 void Serialize(System::IO::TextWriter ^ textWriter, System::Object ^ o, System::Xml::Serialization::XmlSerializerNamespaces ^ namespaces);
public void Serialize (System.IO.TextWriter textWriter, object o, System.Xml.Serialization.XmlSerializerNamespaces namespaces);
member this.Serialize : System.IO.TextWriter * obj * System.Xml.Serialization.XmlSerializerNamespaces -> unit
Public Sub Serialize (textWriter As TextWriter, o As Object, namespaces As XmlSerializerNamespaces)

매개 변수

textWriter
TextWriter

XML 문서를 쓰는 데 사용되는 TextWriter입니다.The TextWriter used to write the XML document.

o
Object

serialize할 Object입니다.The Object to serialize.

namespaces
XmlSerializerNamespaces

생성된 XML 문서의 네임스페이스를 포함하는 XmlSerializerNamespaces입니다.The XmlSerializerNamespaces that contains namespaces for the generated XML document.

예외

serialization 중 오류가 발생했습니다.An error occurred during serialization. InnerException 속성을 사용하여 원래 예외를 사용할 수 있습니다.The original exception is available using the InnerException property.

예제

다음 예제에서는를 사용 하 여 개체를 serialize 합니다 TextWriter .The following example serializes an object with a TextWriter. 또한이 예제에서는 XmlSerializerNamespaces 개체를 만들고 두 개의 네임 스페이스를 개체에 추가 합니다.The example also creates an XmlSerializerNamespaces object and adds two namespaces to the object. Serialize 된 개체를 정의 하는 클래스는 특성으로 XmlElementAttribute 특성을 지정 하 여 각 요소에 대 한 네임 스페이스를 지정 합니다.The class that defines the serialized object is also attributed with XmlElementAttribute attributes to specify the namespace for each element.

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

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

// This is the class that will be serialized.
public ref class OrderedItem
{
public:

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

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

   [XmlElement(Namespace="http://www.cohowinery.com")]
   Decimal UnitPrice;

   [XmlElement(Namespace="http://www.cpandl.com")]
   int Quantity;

   [XmlElement(Namespace="http://www.cohowinery.com")]
   Decimal LineTotal;

   // A custom method used to calculate price per item.
   void Calculate()
   {
      LineTotal = UnitPrice * Quantity;
   }
};

void SerializeObject( String^ filename )
{
   Console::WriteLine( "Writing With TextWriter" );

   // Create an XmlSerializer instance using the type.
   XmlSerializer^ serializer = gcnew XmlSerializer( OrderedItem::typeid );
   OrderedItem^ i = gcnew OrderedItem;
   i->ItemName = "Widget";
   i->Description = "Regular Widget";
   i->Quantity = 10;
   i->UnitPrice = (Decimal)2.30;
   i->Calculate();

   // Create an XmlSerializerNamespaces object.
   XmlSerializerNamespaces^ ns = gcnew XmlSerializerNamespaces;

   // Add two namespaces with prefixes.
   ns->Add( "inventory", "http://www.cpandl.com" );
   ns->Add( "money", "http://www.cohowinery.com" );

   // Create a StreamWriter to write with.
   TextWriter^ writer = gcnew StreamWriter( filename );

   /* Serialize using the object using the TextWriter 
      and namespaces. */
   serializer->Serialize( writer, i, ns );
   writer->Close();
}

int main()
{
   // Write a purchase order.
   SerializeObject( "simple.xml" );
}
using System;
using System.IO;
using System.Xml.Serialization;

// This is the class that will be serialized.
public class OrderedItem
{
   [XmlElement(Namespace = "http://www.cpandl.com")]
   public string ItemName;
   [XmlElement(Namespace = "http://www.cpandl.com")]
   public string Description;
   [XmlElement(Namespace="http://www.cohowinery.com")]
   public decimal UnitPrice;
   [XmlElement(Namespace = "http://www.cpandl.com")]
   public int Quantity;
   [XmlElement(Namespace="http://www.cohowinery.com")]
   public decimal LineTotal;
   // A custom method used to calculate price per item.
   public void Calculate()
   {
      LineTotal = UnitPrice * Quantity;
   }
}

public class Test{
   public static void Main(string[] args)
   {
      Test t = new Test();
      // Write a purchase order.
      t.SerializeObject("simple.xml");
   }

   private void SerializeObject(string filename)
   {
      Console.WriteLine("Writing With TextWriter");
      // Create an XmlSerializer instance using the type.
      XmlSerializer serializer =
      new XmlSerializer(typeof(OrderedItem));
      OrderedItem i = new OrderedItem();
      i.ItemName = "Widget";
      i.Description = "Regular Widget";
      i.Quantity = 10;
      i.UnitPrice = (decimal) 2.30;
      i.Calculate();

      // Create an XmlSerializerNamespaces object.
      XmlSerializerNamespaces ns =
      new XmlSerializerNamespaces();
      // Add two namespaces with prefixes.
      ns.Add("inventory", "http://www.cpandl.com");
      ns.Add("money", "http://www.cohowinery.com");
      // Create a StreamWriter to write with.
      TextWriter writer = new StreamWriter(filename);
      /* Serialize using the object using the TextWriter
      and namespaces. */
      serializer.Serialize(writer, i, ns);
      writer.Close();
   }
}

Imports System.IO
Imports System.Xml.Serialization


' This is the class that will be serialized.
Public Class OrderedItem
    <XmlElement(Namespace := "http://www.cpandl.com")> _
    Public ItemName As String
    
    <XmlElement(Namespace := "http://www.cpandl.com")> _
    Public Description As String
    
    <XmlElement(Namespace := "http://www.cohowinery.com")> _
    Public UnitPrice As Decimal
    
    <XmlElement(Namespace := "http://www.cpandl.com")> _
    Public Quantity As Integer
    
    <XmlElement(Namespace := "http://www.cohowinery.com")> _
    Public LineTotal As Decimal
    
    'A custom method used to calculate price per item.
    Public Sub Calculate()
        LineTotal = UnitPrice * Quantity
    End Sub
End Class


Public Class Test
    
    Public Shared Sub Main()
        Dim t As New Test()
        ' Write a purchase order.
        t.SerializeObject("simple.xml")
    End Sub
    
    Private Sub SerializeObject(ByVal filename As String)
        Console.WriteLine("Writing With TextWriter")
        ' Create an XmlSerializer instance using the type.
        Dim serializer As New XmlSerializer(GetType(OrderedItem))
        Dim i As New OrderedItem()
        i.ItemName = "Widget"
        i.Description = "Regular Widget"
        i.Quantity = 10
        i.UnitPrice = CDec(2.3)
        i.Calculate()
        
        ' Create an XmlSerializerNamespaces object.
        Dim ns As New XmlSerializerNamespaces()
        ' Add two namespaces with prefixes.
        ns.Add("inventory", "http://www.cpandl.com")
        ns.Add("money", "http://www.cohowinery.com")
        ' Create a StreamWriter to write with.
        Dim writer As New StreamWriter(filename)
        ' Serialize using the object using the TextWriter
        ' and namespaces. 
        serializer.Serialize(writer, i, ns)
        writer.Close()
    End Sub
End Class

<?xml version="1.0"?>
 <OrderedItem xmlns:inventory="http://www.cpandl.com" xmlns:money="http://www.cohowinery.com">
   <inventory:ItemName>Widget</inventory:ItemName>
   <inventory:Description>Regular Widget</inventory:Description>
   <money:UnitPrice>2.3</money:UnitPrice>
   <inventory:Quantity>10</inventory:Quantity>
   <money:LineTotal>23</money:LineTotal>
 </OrderedItem>

설명

Serialize메서드가 호출 되 면 public 필드와 개체의 읽기/쓰기 속성이 XML로 변환 됩니다.When the Serialize method is invoked the public fields and read/write properties of an object are converted into XML. 메서드, 인덱서, 전용 필드 및 읽기 전용 속성은 serialize 되지 않습니다.Methods, indexers, private fields, and read-only properties are not serialized. Public 및 private의 모든 필드와 속성을 serialize 하려면를 사용 BinaryFormatter 합니다.To serialize all fields and properties, both public and private, use the BinaryFormatter.

textWriter매개 변수를 사용 하 여 추상 클래스에서 파생 되는 개체를 지정 TextWriter 합니다.Use the textWriter parameter to specify an object that derives from the abstract TextWriter class. 클래스에서 파생 되는 클래스는 TextWriter 다음과 같습니다.Classes that derive from TextWriter class include:

참고

는의 배열과 배열의 배열을 XmlSerializer serialize 할 수 없습니다. ArrayList List<T>The XmlSerializer cannot serialize the following: arrays of ArrayList and arrays of List<T>.

추가 정보

Serialize(Object, XmlSerializationWriter)

지정된 Object를 serialize하고 지정된 XmlSerializationWriter을 사용하여 XML 문서를 파일에 씁니다.Serializes the specified Object and writes the XML document to a file using the specified XmlSerializationWriter.

protected:
 virtual void Serialize(System::Object ^ o, System::Xml::Serialization::XmlSerializationWriter ^ writer);
protected virtual void Serialize (object o, System.Xml.Serialization.XmlSerializationWriter writer);
abstract member Serialize : obj * System.Xml.Serialization.XmlSerializationWriter -> unit
override this.Serialize : obj * System.Xml.Serialization.XmlSerializationWriter -> unit
Protected Overridable Sub Serialize (o As Object, writer As XmlSerializationWriter)

매개 변수

o
Object

serialize할 Object입니다.The Object to serialize.

writer
XmlSerializationWriter

XML 문서를 쓰는 데 사용되는 XmlSerializationWriter입니다.The XmlSerializationWriter used to write the XML document.

예외

하위 클래스에서 재정의되지 않은 메서드에 액세스하려는 경우Any attempt is made to access the method when the method is not overridden in a descendant class.

Serialize(TextWriter, Object)

지정된 Object를 serialize하고 지정된 TextWriter을 사용하여 XML 문서를 파일에 씁니다.Serializes the specified Object and writes the XML document to a file using the specified TextWriter.

public:
 void Serialize(System::IO::TextWriter ^ textWriter, System::Object ^ o);
public void Serialize (System.IO.TextWriter textWriter, object o);
member this.Serialize : System.IO.TextWriter * obj -> unit
Public Sub Serialize (textWriter As TextWriter, o As Object)

매개 변수

textWriter
TextWriter

XML 문서를 쓰는 데 사용되는 TextWriter입니다.The TextWriter used to write the XML document.

o
Object

serialize할 Object입니다.The Object to serialize.

예제

다음 예제에서는를 사용 하 여 개체를 serialize 합니다 TextWriter .The following example serializes an object using a TextWriter.

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

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

// This is the class that will be serialized.
public ref class OrderedItem
{
public:
   String^ ItemName;
   String^ Description;
   Decimal UnitPrice;
   int Quantity;
   Decimal LineTotal;

   // A custom method used to calculate price per item.
   void Calculate()
   {
      LineTotal = UnitPrice * Quantity;
   }
};

void SerializeObject( String^ filename )
{
   Console::WriteLine( "Writing With TextWriter" );
   XmlSerializer^ serializer = gcnew XmlSerializer( OrderedItem::typeid );
   OrderedItem^ i = gcnew OrderedItem;
   i->ItemName = "Widget";
   i->Description = "Regular Widget";
   i->Quantity = 10;
   i->UnitPrice = (Decimal)2.30;
   i->Calculate();

   /* Create a StreamWriter to write with. First create a FileStream
      object, and create the StreamWriter specifying an Encoding to use. */
   FileStream^ fs = gcnew FileStream( filename,FileMode::Create );
   TextWriter^ writer = gcnew StreamWriter( fs,gcnew UTF8Encoding );

   // Serialize using the XmlTextWriter.
   serializer->Serialize( writer, i );
   writer->Close();
}

int main()
{
   // Write a purchase order.
   SerializeObject( "simple.xml" );
}
using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;

// This is the class that will be serialized.
public class OrderedItem
{
   public string ItemName;
   public string Description;
   public decimal UnitPrice;
   public int Quantity;
   public decimal LineTotal;
   // A custom method used to calculate price per item.
   public void Calculate()
   {
      LineTotal = UnitPrice * Quantity;
   }
}

public class Test{
   public static void Main(string[] args)
   {
      Test t = new Test();
      // Write a purchase order.
      t.SerializeObject("simple.xml");
   }

  private void SerializeObject(string filename)
  {
      Console.WriteLine("Writing With TextWriter");

      XmlSerializer serializer =
      new XmlSerializer(typeof(OrderedItem));
      OrderedItem i = new OrderedItem();
      i.ItemName = "Widget";
      i.Description = "Regular Widget";
      i.Quantity = 10;
      i.UnitPrice = (decimal) 2.30;
      i.Calculate();

      /* Create a StreamWriter to write with. First create a FileStream
         object, and create the StreamWriter specifying an Encoding to use. */
      FileStream fs = new FileStream(filename, FileMode.Create);
      TextWriter writer = new StreamWriter(fs, new UTF8Encoding());
      // Serialize using the XmlTextWriter.
      serializer.Serialize(writer, i);
      writer.Close();
   }
}

Imports System.IO
Imports System.Text
Imports System.Xml.Serialization


' 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
    Public LineTotal As Decimal
    
    'A custom method used to calculate price per item.
    Public Sub Calculate()
        LineTotal = UnitPrice * Quantity
    End Sub
End Class


Public Class Test
    
    Public Shared Sub Main()
        Dim t As New Test()
        ' Write a purchase order.
        t.SerializeObject("simple.xml")
    End Sub
    
    Private Sub SerializeObject(ByVal filename As String)
        Console.WriteLine("Writing With TextWriter")
        
        Dim serializer As New XmlSerializer(GetType(OrderedItem))
        Dim i As New OrderedItem()

        With i
            .ItemName = "Widget"
            .Description = "Regular Widget"
            .Quantity = 10
            .UnitPrice = CDec(2.3)
            .Calculate()
        End With
        
        ' Create a StreamWriter to write with. First create a FileStream
        ' object, and create the StreamWriter specifying an Encoding to use. 
        Dim fs As New FileStream(filename, FileMode.Create)
        Dim writer As New StreamWriter(fs, New UTF8Encoding())
        ' Serialize using the XmlTextWriter.
        serializer.Serialize(writer, i)
        writer.Close()
    End Sub
End Class

<?xml version="1.0"?>
 <OrderedItem xmlns:inventory="http://www.cpandl.com" xmlns:money="http://www.cohowinery.com">
   <inventory:ItemName>Widget</inventory:ItemName>
   <inventory:Description>Regular Widget</inventory:Description>
   <money:UnitPrice>2.3</money:UnitPrice>
   <inventory:Quantity>10</inventory:Quantity>
   <money:LineTotal>23</money:LineTotal>
 </OrderedItem>

설명

Serialize메서드는 개체의 공용 필드 및 읽기/쓰기 속성을 XML로 변환 합니다.The Serialize method converts the public fields and read/write properties of an object into XML. 메서드, 인덱서, 전용 필드 또는 읽기 전용 속성을 변환 하지 않습니다.It does not convert methods, indexers, private fields, or read-only properties. Public 및 private의 모든 개체의 필드와 속성을 serialize 하려면를 사용 BinaryFormatter 합니다.To serialize all an object's fields and properties, both public and private, use the BinaryFormatter.

textWriter매개 변수에서 추상 클래스에서 파생 되는 개체를 지정 TextWriter 합니다.In the textWriter parameter, specify an object that derives from the abstract TextWriter class. 에서 파생 되는 클래스는 TextWriter 다음과 같습니다.Classes that derive from TextWriter include:

참고

는의 배열과 배열의 배열을 XmlSerializer serialize 할 수 없습니다. ArrayList List<T>The XmlSerializer cannot serialize the following: arrays of ArrayList and arrays of List<T>.

추가 정보

Serialize(Stream, Object)

지정된 Object를 serialize하고 지정된 Stream을 사용하여 XML 문서를 파일에 씁니다.Serializes the specified Object and writes the XML document to a file using the specified Stream.

public:
 void Serialize(System::IO::Stream ^ stream, System::Object ^ o);
public void Serialize (System.IO.Stream stream, object o);
member this.Serialize : System.IO.Stream * obj -> unit
Public Sub Serialize (stream As Stream, o As Object)

매개 변수

stream
Stream

XML 문서를 쓰는 데 사용되는 Stream입니다.The Stream used to write the XML document.

o
Object

serialize할 Object입니다.The Object to serialize.

예외

serialization 중 오류가 발생했습니다.An error occurred during serialization. InnerException 속성을 사용하여 원래 예외를 사용할 수 있습니다.The original exception is available using the InnerException property.

예제

다음 예제에서는 개체를 사용 하 여 개체를 serialize 합니다 Stream .The following example serializes an object using a Stream object.

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

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

// This is the class that will be serialized.
public ref class OrderedItem
{
public:
   String^ ItemName;
   String^ Description;
   Decimal UnitPrice;
   int Quantity;
   Decimal LineTotal;

   // A custom method used to calculate price per item.
   void Calculate()
   {
      LineTotal = UnitPrice * Quantity;
   }
};

void SerializeObject( String^ filename )
{
   Console::WriteLine( "Writing With Stream" );
   XmlSerializer^ serializer = gcnew XmlSerializer( OrderedItem::typeid );
   OrderedItem^ i = gcnew OrderedItem;
   i->ItemName = "Widget";
   i->Description = "Regular Widget";
   i->Quantity = 10;
   i->UnitPrice = (Decimal)2.30;
   i->Calculate();

   // Create a FileStream to write with.
   Stream^ writer = gcnew FileStream( filename,FileMode::Create );

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

int main()
{
   // Write a purchase order.
   SerializeObject( "simple.xml" );
}
using System;
using System.IO;
using System.Xml.Serialization;

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

   // A custom method used to calculate price per item.
   public void Calculate()
   {
      LineTotal = UnitPrice * Quantity;
   }
}

public class Test{
   public static void Main(string[] args)
   {
      Test t = new Test();
      // Write a purchase order.
      t.SerializeObject("simple.xml");
   }

   private void SerializeObject(string filename)
   {
      Console.WriteLine("Writing With Stream");

      XmlSerializer serializer =
      new XmlSerializer(typeof(OrderedItem));
      OrderedItem i = new OrderedItem();
      i.ItemName = "Widget";
      i.Description = "Regular Widget";
      i.Quantity = 10;
      i.UnitPrice = (decimal) 2.30;
      i.Calculate();

      // Create a FileStream to write with.
      Stream writer = new FileStream(filename, FileMode.Create);
      // Serialize the object, and close the TextWriter
      serializer.Serialize(writer, i);
      writer.Close();
   }
}

Imports System.IO
Imports System.Xml.Serialization


' 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
    Public LineTotal As Decimal
    
    
    ' A custom method used to calculate price per item.
    Public Sub Calculate()
        LineTotal = UnitPrice * Quantity
    End Sub
End Class


Public Class Test
    
    Public Shared Sub Main()
        Dim t As New Test()
        ' Write a purchase order.
        t.SerializeObject("simple.xml")
    End Sub
    
    Private Sub SerializeObject(ByVal filename As String)
        Console.WriteLine("Writing With Stream")
        
        Dim serializer As New XmlSerializer(GetType(OrderedItem))
        Dim i As New OrderedItem()

        With i
            .ItemName = "Widget"
            .Description = "Regular Widget"
            .Quantity = 10
            .UnitPrice = CDec(2.3)
            .Calculate()
        End With
        
        ' Create a FileStream to write with.
        Dim writer As New FileStream(filename, FileMode.Create)
        ' Serialize the object, and close the TextWriter
        serializer.Serialize(writer, i)
        writer.Close()
    End Sub
End Class

<?xml version="1.0"?>
 <OrderedItem xmlns:inventory="http://www.cpandl.com" xmlns:money="http://www.cohowinery.com">
   <inventory:ItemName>Widget</inventory:ItemName>
   <inventory:Description>Regular Widget</inventory:Description>
   <money:UnitPrice>2.3</money:UnitPrice>
   <inventory:Quantity>10</inventory:Quantity>
   <money:LineTotal>23</money:LineTotal>
 </OrderedItem>

설명

Serialize메서드는 개체의 공용 필드 및 읽기/쓰기 속성을 XML로 변환 합니다.The Serialize method converts the public fields and read/write properties of an object into XML. 메서드, 인덱서, 전용 필드 또는 읽기 전용 속성을 변환 하지 않습니다.It does not convert methods, indexers, private fields, or read-only properties. Public 및 private의 모든 개체 필드와 속성을 serialize 하려면를 사용 BinaryFormatter 합니다.To serialize all of an object's fields and properties, both public and private, use the BinaryFormatter.

stream매개 변수에서 추상 클래스에서 파생 되는 개체를 지정 Stream 합니다.In the stream parameter, specify an object that derives from the abstract Stream class. 에서 파생 되는 클래스는 Stream 다음과 같습니다.Classes that derive from Stream include:

참고

는의 배열과 배열의 배열을 XmlSerializer serialize 할 수 없습니다. ArrayList List<T>The XmlSerializer cannot serialize the following: arrays of ArrayList and arrays of List<T>.

추가 정보

Serialize(Stream, Object, XmlSerializerNamespaces)

지정된 Object를 serialize하고 지정된 네임스페이스를 참조하는 지정된 Stream을 사용하여 XML 문서를 파일에 씁니다.Serializes the specified Object and writes the XML document to a file using the specified Stream that references the specified namespaces.

public:
 void Serialize(System::IO::Stream ^ stream, System::Object ^ o, System::Xml::Serialization::XmlSerializerNamespaces ^ namespaces);
public void Serialize (System.IO.Stream stream, object o, System.Xml.Serialization.XmlSerializerNamespaces namespaces);
member this.Serialize : System.IO.Stream * obj * System.Xml.Serialization.XmlSerializerNamespaces -> unit
Public Sub Serialize (stream As Stream, o As Object, namespaces As XmlSerializerNamespaces)

매개 변수

stream
Stream

XML 문서를 쓰는 데 사용되는 Stream입니다.The Stream used to write the XML document.

o
Object

serialize할 Object입니다.The Object to serialize.

namespaces
XmlSerializerNamespaces

개체에서 참조하는 XmlSerializerNamespaces입니다.The XmlSerializerNamespaces referenced by the object.

예외

serialization 중 오류가 발생했습니다.An error occurred during serialization. InnerException 속성을 사용하여 원래 예외를 사용할 수 있습니다.The original exception is available using the InnerException property.

예제

다음 예제에서는 개체를 사용 하 여 개체를 serialize 합니다 Stream .The following example serializes an object with a Stream object. 또한이 예제에서는를 만들고 XmlSerializerNamespaces 두 개의 네임 스페이스를 개체에 추가 합니다.The example also creates an XmlSerializerNamespaces and adds two namespaces to the object. Serialize 된 개체를 정의 하는 클래스는 특성으로 XmlElementAttribute 특성을 지정 하 여 각 요소에 대 한 네임 스페이스를 지정 합니다.The class that defines the serialized object is also attributed with XmlElementAttribute attributes to specify the namespace for each element.

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

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

// This is the class that will be serialized.
public ref class OrderedItem
{
public:

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

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

   [XmlElement(Namespace="http://www.cohowinery.com")]
   Decimal UnitPrice;

   [XmlElement(Namespace="http://www.cpandl.com")]
   int Quantity;

   [XmlElement(Namespace="http://www.cohowinery.com")]
   Decimal LineTotal;

   // A custom method used to calculate price per item.
   void Calculate()
   {
      LineTotal = UnitPrice * Quantity;
   }
};

void SerializeObject( String^ filename )
{
   Console::WriteLine( "Writing With Stream" );
   XmlSerializer^ serializer = gcnew XmlSerializer( OrderedItem::typeid );
   OrderedItem^ i = gcnew OrderedItem;
   i->ItemName = "Widget";
   i->Description = "Regular Widget";
   i->Quantity = 10;
   i->UnitPrice = (Decimal)2.30;
   i->Calculate();

   // Create an XmlSerializerNamespaces object.
   XmlSerializerNamespaces^ ns = gcnew XmlSerializerNamespaces;

   // Add two prefix-namespace pairs.
   ns->Add( "inventory", "http://www.cpandl.com" );
   ns->Add( "money", "http://www.cohowinery.com" );

   // Create a FileStream to write with.
   Stream^ writer = gcnew FileStream( filename,FileMode::Create );

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

void DeserializeObject( String^ filename )
{
   Console::WriteLine( "Reading with Stream" );

   // Create an instance of the XmlSerializer.
   XmlSerializer^ serializer = gcnew XmlSerializer( OrderedItem::typeid );

   // Writing the file requires a Stream.
   Stream^ reader = gcnew FileStream( filename,FileMode::Open );

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

   /* Use the Deserialize method to restore the object's state 
      using data from the XML document. */
   i = dynamic_cast<OrderedItem^>(serializer->Deserialize( reader ));

   // Write out the properties of the object.
   Console::Write( "{0}\t{1}\t{2}\t{3}\t{4}", i->ItemName, i->Description, i->UnitPrice, i->Quantity, i->LineTotal );
}

int main()
{
   // Write a purchase order.
   SerializeObject( "simple.xml" );
   DeserializeObject( "simple.xml" );
}

using System;
using System.IO;
using System.Xml.Serialization;

// This is the class that will be serialized.
public class OrderedItem {
    [XmlElement(Namespace = "http://www.cpandl.com")]
    public string ItemName;
    [XmlElement(Namespace = "http://www.cpandl.com")]
    public string Description;
    [XmlElement(Namespace="http://www.cohowinery.com")]
    public decimal UnitPrice;
    [XmlElement(Namespace = "http://www.cpandl.com")]
    public int Quantity;
    [XmlElement(Namespace="http://www.cohowinery.com")]
    public decimal LineTotal;

    // A custom method used to calculate price per item.
    public void Calculate() {
        LineTotal = UnitPrice * Quantity;
    }
}

public class Test {

   public static void Main() {
        Test t = new Test();
        // Write a purchase order.
        t.SerializeObject("simple.xml");
        t.DeserializeObject("simple.xml");
   }

   private void SerializeObject(string filename) {
        Console.WriteLine("Writing With Stream");

        XmlSerializer serializer =
            new XmlSerializer(typeof(OrderedItem));

        OrderedItem i = new OrderedItem();
        i.ItemName = "Widget";
        i.Description = "Regular Widget";
        i.Quantity = 10;
        i.UnitPrice = (decimal) 2.30;
        i.Calculate();

        // Create an XmlSerializerNamespaces object.
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

        // Add two prefix-namespace pairs.
        ns.Add("inventory", "http://www.cpandl.com");
        ns.Add("money", "http://www.cohowinery.com");

        // Create a FileStream to write with.
        Stream writer = new FileStream(filename, FileMode.Create);

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

    private void DeserializeObject(string filename) {
        Console.WriteLine("Reading with Stream");
        // Create an instance of the XmlSerializer.
        XmlSerializer serializer = new XmlSerializer(typeof(OrderedItem));

        // Writing the file requires a Stream.
        Stream reader= new FileStream(filename,FileMode.Open);

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

        /* Use the Deserialize method to restore the object's state
           using data from the XML document. */
        i = (OrderedItem) serializer.Deserialize(reader);

        // Write out the properties of the object.
        Console.Write(
            i.ItemName + "\t" +
            i.Description + "\t" +
            i.UnitPrice + "\t" +
            i.Quantity + "\t" +
            i.LineTotal);
    }
}

Imports System.IO
Imports System.Xml.Serialization

' This is the class that will be serialized.
Public Class OrderedItem
    <XmlElement(Namespace := "http://www.cpandl.com")> _
    Public ItemName As String
    
    <XmlElement(Namespace := "http://www.cpandl.com")> _
    Public Description As String
    
    <XmlElement(Namespace := "http://www.cohowinery.com")> _
    Public UnitPrice As Decimal
    
    <XmlElement(Namespace := "http://www.cpandl.com")> _
    Public Quantity As Integer
    
    <XmlElement(Namespace := "http://www.cohowinery.com")> _
    Public LineTotal As Decimal
    
    ' A custom method used to calculate price per item.
    Public Sub Calculate()
        LineTotal = UnitPrice * Quantity
    End Sub
End Class

Public Class Test
        
    Public Shared Sub Main()
        Dim t As New Test()
        ' Write a purchase order.
        t.SerializeObject("simple.xml")
        t.DeserializeObject("simple.xml")
    End Sub    
    
    Private Sub SerializeObject(ByVal filename As String)
        Console.WriteLine("Writing With Stream")
        
        Dim serializer As New XmlSerializer(GetType(OrderedItem))
        
        Dim i As New OrderedItem()
        With i
            .ItemName = "Widget"
            .Description = "Regular Widget"
            .Quantity = 10
            .UnitPrice = CDec(2.3)
            .Calculate()
        End With
        
        ' Create an XmlSerializerNamespaces object.
        Dim ns As New XmlSerializerNamespaces()
        
        ' Add two prefix-namespace pairs.
        ns.Add("inventory", "http://www.cpandl.com")
        ns.Add("money", "http://www.cohowinery.com")
        
        ' Create a FileStream to write with.
        Dim writer As New FileStream(filename, FileMode.Create)
        
        ' Serialize the object, and close the TextWriter
        serializer.Serialize(writer, i, ns)
        writer.Close()
    End Sub
        
    Private Sub DeserializeObject(ByVal filename As String)
        Console.WriteLine("Reading with Stream")
        ' Create an instance of the XmlSerializer.
        Dim serializer As New XmlSerializer(GetType(OrderedItem))
        
        ' Writing the file requires a Stream.
        Dim reader As New FileStream(filename, FileMode.Open)
        
        ' Declare an object variable of the type to be deserialized.
        Dim i As OrderedItem
        
        ' Use the Deserialize method to restore the object's state
        ' using data from the XML document. 
        i = CType(serializer.Deserialize(reader), OrderedItem)
        
        ' Write out the properties of the object.
        Console.Write(i.ItemName & ControlChars.Tab & _
                      i.Description & ControlChars.Tab & _
                      i.UnitPrice & ControlChars.Tab & _
                      i.Quantity & ControlChars.Tab & _
                      i.LineTotal)
    End Sub
End Class

설명

Serialize메서드가 호출 되 면 개체의 공용 필드 및 읽기/쓰기 속성이 XML로 변환 됩니다.When the Serialize method is invoked, the public fields and read/write properties of an object are converted into XML. 메서드, 인덱서, 전용 필드 및 읽기 전용 속성은 serialize 되지 않습니다.Methods, indexers, private fields, and read-only properties are not serialized. Public 및 private의 모든 필드와 속성을 serialize 하려면를 사용 BinaryFormatter 합니다.To serialize all fields and properties, both public and private, use the BinaryFormatter.

매개 변수를 사용 하 여 stream Stream 스트림에 쓰도록 디자인 된 추상 클래스에서 파생 되는 개체를 지정 합니다.Use the stream parameter to specify an object that derives from the abstract Stream class, which is designed to write to streams. 파생 된 클래스는 Stream 클래스를 포함 합니다.Classes that derive from the Stream class include:

참고

는의 배열과 배열의 배열을 XmlSerializer serialize 할 수 없습니다. ArrayList List<T>The XmlSerializer cannot serialize the following: arrays of ArrayList and arrays of List<T>.

추가 정보

적용 대상