XmlSerializer.Serialize 方法

定义

将对象序列化到 XML 文档中。Serializes an object into an XML document.

重载

Serialize(XmlWriter, Object)

使用指定的 Object 序列化指定的 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、XML 命名空间和编码序列化指定的 XmlWriter 并将 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)

使用指定的 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 和指定命名空间序列化指定的 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 和指定命名空间序列化指定的 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 序列化指定的 XmlSerializationWriter 并将 XML 文档写入文件。Serializes the specified Object and writes the XML document to a file using the specified XmlSerializationWriter.

Serialize(TextWriter, Object)

使用指定的 Object 序列化指定的 TextWriter 并将 XML 文档写入文件。Serializes the specified Object and writes the XML document to a file using the specified TextWriter.

Serialize(Stream, Object)

使用指定的 Object 序列化指定的 Stream 并将 XML 文档写入文件。Serializes the specified Object and writes the XML document to a file using the specified Stream.

Serialize(Stream, Object, XmlSerializerNamespaces)

使用引用指定命名空间的指定 Object 序列化指定的 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 序列化指定的 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

参数

xmlWriter
XmlWriter

用于编写 XML 文档的 XmlWriterThe XmlWriter used to write the XML document.

o
Object

要序列化的 ObjectThe Object to serialize.

例外

序列化期间发生错误。An error occurred during serialization. 使用 InnerException 属性时可使用原始异常。The original exception is available using the InnerException property.

示例

下面的示例使用 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. 若要序列化对象的所有字段和属性(公共和私有),请使用 BinaryFormatterTo 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 派生自 XmlWriterThe XmlTextWriter derives from the XmlWriter.

备注

XmlSerializer 无法序列化以下内容: List<T>的数组和 ArrayList 的数组。The XmlSerializer cannot serialize the following: arrays of ArrayList and arrays of List<T>.

另请参阅

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

使用指定的 Object、XML 命名空间和编码序列化指定的 XmlWriter 并将 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

参数

xmlWriter
XmlWriter

用于编写 XML 文档的 XmlWriterThe XmlWriter used to write the XML document.

o
Object

要序列化的对象。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)

使用指定的 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

参数

xmlWriter
XmlWriter

用于编写 XML 文档的 XmlWriterThe XmlWriter used to write the XML document.

o
Object

要序列化的对象。The object to serialize.

namespaces
XmlSerializerNamespaces

该对象所引用的 XmlSerializerNamespacesThe XmlSerializerNamespaces referenced by the object.

encodingStyle
String

序列化的 XML 的编码样式。The encoding style of the serialized XML.

例外

序列化期间发生错误。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. 不序列化方法、索引器、私有字段和只读属性。Methods, indexers, private fields, and read-only properties are not serialized. 若要序列化所有字段和属性(无论是公共的还是私有的),请使用 BinaryFormatterTo serialize all fields and properties, both public and private, use the BinaryFormatter.

使用 xmlWriter 参数来指定派生自抽象 XmlWriter 类的对象,该类用于写入 XML 文档。Use the xmlWriter parameter to specify an object that derives from the abstract XmlWriter class, which is designed to write XML documents. XmlTextWriter 派生自 XmlWriterThe XmlTextWriter derives from the XmlWriter.

将 SOAP 版本1.1 编码的 encodingStyle 参数设置为 "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 无法序列化以下内容: List<T>的数组和 ArrayList 的数组。The XmlSerializer cannot serialize the following: arrays of ArrayList and arrays of List<T>.

另请参阅

Serialize(XmlWriter, Object, XmlSerializerNamespaces)

使用指定的 Object 和指定命名空间序列化指定的 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

参数

xmlWriter
XmlWriter

用于编写 XML 文档的 XmlWriterThe XmlWriter used to write the XML document.

o
Object

要序列化的 ObjectThe Object to serialize.

namespaces
XmlSerializerNamespaces

该对象所引用的 XmlSerializerNamespacesThe XmlSerializerNamespaces referenced by the object.

例外

序列化期间发生错误。An error occurred during serialization. 使用 InnerException 属性时可使用原始异常。The original exception is available using the InnerException property.

示例

下面的示例使用 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. 不序列化方法、索引器、私有字段和只读属性。Methods, indexers, private fields, and read-only properties are not serialized. 若要序列化所有字段和属性(无论是公共的还是私有的),请使用 BinaryFormatterTo serialize all fields and properties, both public and private, use the BinaryFormatter.

使用 xmlWriter 参数来指定派生自抽象 XmlWriter 类的对象,该类用于写入 XML 文档。Use the xmlWriter parameter to specify an object that derives from the abstract XmlWriter class, which is designed to write XML documents. XmlTextWriter 派生自 XmlWriterThe XmlTextWriter derives from the XmlWriter.

备注

XmlSerializer 无法序列化以下内容: List<T>的数组和 ArrayList 的数组。The XmlSerializer cannot serialize the following: arrays of ArrayList and arrays of List<T>.

另请参阅

Serialize(TextWriter, Object, XmlSerializerNamespaces)

使用指定的 Object 和指定命名空间序列化指定的 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

参数

textWriter
TextWriter

用于编写 XML 文档的 TextWriterThe TextWriter used to write the XML document.

o
Object

要序列化的 ObjectThe Object to serialize.

namespaces
XmlSerializerNamespaces

包含生成的 XML 文档的命名空间的 XmlSerializerNamespacesThe XmlSerializerNamespaces that contains namespaces for the generated XML document.

例外

序列化期间发生错误。An error occurred during serialization. 使用 InnerException 属性时可使用原始异常。The original exception is available using the InnerException property.

示例

下面的示例使用 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. 定义序列化对象的类也用 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 方法时,对象的公共字段和读/写属性将转换为 XML。When the Serialize method is invoked the public fields and read/write properties of an object are converted into XML. 不序列化方法、索引器、私有字段和只读属性。Methods, indexers, private fields, and read-only properties are not serialized. 若要序列化所有字段和属性(无论是公共的还是私有的),请使用 BinaryFormatterTo 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 无法序列化以下内容: List<T>的数组和 ArrayList 的数组。The XmlSerializer cannot serialize the following: arrays of ArrayList and arrays of List<T>.

另请参阅

Serialize(Object, XmlSerializationWriter)

使用指定的 Object 序列化指定的 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

要序列化的 ObjectThe Object to serialize.

writer
XmlSerializationWriter

用于编写 XML 文档的 XmlSerializationWriterThe 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 序列化指定的 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

参数

textWriter
TextWriter

用于编写 XML 文档的 TextWriterThe TextWriter used to write the XML document.

o
Object

要序列化的 ObjectThe Object to 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. 若要序列化对象的所有字段和属性(公共和私有),请使用 BinaryFormatterTo 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 无法序列化以下内容: List<T>的数组和 ArrayList 的数组。The XmlSerializer cannot serialize the following: arrays of ArrayList and arrays of List<T>.

另请参阅

Serialize(Stream, Object)

使用指定的 Object 序列化指定的 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

参数

stream
Stream

用于编写 XML 文档的 StreamThe Stream used to write the XML document.

o
Object

要序列化的 ObjectThe Object to serialize.

例外

序列化期间发生错误。An error occurred during serialization. 使用 InnerException 属性时可使用原始异常。The original exception is available using the InnerException property.

示例

下面的示例使用 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. 若要序列化对象的所有字段和属性(公共和私有),请使用 BinaryFormatterTo 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 无法序列化以下内容: List<T>的数组和 ArrayList 的数组。The XmlSerializer cannot serialize the following: arrays of ArrayList and arrays of List<T>.

另请参阅

Serialize(Stream, Object, XmlSerializerNamespaces)

使用引用指定命名空间的指定 Object 序列化指定的 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

参数

stream
Stream

用于编写 XML 文档的 StreamThe Stream used to write the XML document.

o
Object

要序列化的 ObjectThe Object to serialize.

namespaces
XmlSerializerNamespaces

该对象所引用的 XmlSerializerNamespacesThe XmlSerializerNamespaces referenced by the object.

例外

序列化期间发生错误。An error occurred during serialization. 使用 InnerException 属性时可使用原始异常。The original exception is available using the InnerException property.

示例

下面的示例使用 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. 定义序列化对象的类也用 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. 不序列化方法、索引器、私有字段和只读属性。Methods, indexers, private fields, and read-only properties are not serialized. 若要序列化所有字段和属性(无论是公共的还是私有的),请使用 BinaryFormatterTo 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 无法序列化以下内容: List<T>的数组和 ArrayList 的数组。The XmlSerializer cannot serialize the following: arrays of ArrayList and arrays of List<T>.

另请参阅

适用于