XmlSerializer XmlSerializer XmlSerializer XmlSerializer Class

定義

將物件序列化成為 XML 文件,以及從 XML 文件將物件還原序列化。Serializes and deserializes objects into and from XML documents. XmlSerializer 可讓您控制如何將物件編碼為 XML。The XmlSerializer enables you to control how objects are encoded into XML.

public ref class XmlSerializer
public class XmlSerializer
type XmlSerializer = class
Public Class XmlSerializer
繼承
XmlSerializerXmlSerializerXmlSerializerXmlSerializer

範例

下列範例包含兩個主要類別:PurchaseOrderTestThe following example contains two main classes: PurchaseOrder and Test. PurchaseOrder類別包含單一的採購單的相關資訊。The PurchaseOrder class contains information about a single purchase. Test類別包含建立訂單,以及讀取建立的訂單的方法。The Test class contains the methods that create the purchase order, and that read the created purchase order.

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

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

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

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

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

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

public ref class Address
{
public:

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

   [XmlAttributeAttribute]
   String^ Name;
   String^ Line1;

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

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

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

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

};

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

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

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

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

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

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

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

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

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

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

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

      // A FileStream is needed to read the XML document.
      FileStream^ fs = gcnew FileStream( filename,FileMode::Open );

      // Declare an object variable of the type to be deserialized.
      PurchaseOrder^ po;

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

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

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

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

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

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

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

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

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

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

   /* Setting the IsNullable property to false instructs the 
      XmlSerializer that the XML attribute will not appear if 
      the City field is set to a null reference. */
   [XmlElementAttribute(IsNullable = false)]
   public string City;
   public string State;
   public string Zip;
}
 
public class OrderedItem
{
   public string ItemName;
   public string Description;
   public decimal UnitPrice;
   public int Quantity;
   public decimal LineTotal;

   /* Calculate is a custom method that calculates the price per item,
      and stores the value in a field. */
   public void Calculate()
   {
      LineTotal = UnitPrice * Quantity;
   }
}
 
public class Test
{
   public static void Main()
   {
      // Read and write purchase orders.
      Test t = new Test();
      t.CreatePO("po.xml");
      t.ReadPO("po.xml");
   }

   private void CreatePO(string filename)
   {
      // Create an instance of the XmlSerializer class;
      // specify the type of object to serialize.
      XmlSerializer serializer = 
      new XmlSerializer(typeof(PurchaseOrder));
      TextWriter writer = new StreamWriter(filename);
      PurchaseOrder po=new PurchaseOrder();
       
      // Create an address to ship and bill to.
      Address billAddress = new Address();
      billAddress.Name = "Teresa Atkinson";
      billAddress.Line1 = "1 Main St.";
      billAddress.City = "AnyTown";
      billAddress.State = "WA";
      billAddress.Zip = "00000";
      // Set ShipTo and BillTo to the same addressee.
      po.ShipTo = billAddress;
      po.OrderDate = System.DateTime.Now.ToLongDateString();
 
      // Create an OrderedItem object.
      OrderedItem i1 = new OrderedItem();
      i1.ItemName = "Widget S";
      i1.Description = "Small widget";
      i1.UnitPrice = (decimal) 5.23;
      i1.Quantity = 3;
      i1.Calculate();
 
      // Insert the item into the array.
      OrderedItem [] items = {i1};
      po.OrderedItems = items;
      // Calculate the total cost.
      decimal subTotal = new decimal();
      foreach(OrderedItem oi in items)
      {
         subTotal += oi.LineTotal;
      }
      po.SubTotal = subTotal;
      po.ShipCost = (decimal) 12.51; 
      po.TotalCost = po.SubTotal + po.ShipCost; 
      // Serialize the purchase order, and close the TextWriter.
      serializer.Serialize(writer, po);
      writer.Close();
   }
 
   protected void ReadPO(string filename)
   {
      // Create an instance of the XmlSerializer class;
      // specify the type of object to be deserialized.
      XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder));
      /* If the XML document has been altered with unknown 
      nodes or attributes, handle them with the 
      UnknownNode and UnknownAttribute events.*/
      serializer.UnknownNode+= new 
      XmlNodeEventHandler(serializer_UnknownNode);
      serializer.UnknownAttribute+= new 
      XmlAttributeEventHandler(serializer_UnknownAttribute);
   
      // A FileStream is needed to read the XML document.
      FileStream fs = new FileStream(filename, FileMode.Open);
      // Declare an object variable of the type to be deserialized.
      PurchaseOrder po;
      /* Use the Deserialize method to restore the object's state with
      data from the XML document. */
      po = (PurchaseOrder) serializer.Deserialize(fs);
      // Read the order date.
      Console.WriteLine ("OrderDate: " + po.OrderDate);
  
      // Read the shipping address.
      Address shipTo = po.ShipTo;
      ReadAddress(shipTo, "Ship To:");
      // Read the list of ordered items.
      OrderedItem [] items = po.OrderedItems;
      Console.WriteLine("Items to be shipped:");
      foreach(OrderedItem oi in items)
      {
         Console.WriteLine("\t"+
         oi.ItemName + "\t" + 
         oi.Description + "\t" +
         oi.UnitPrice + "\t" +
         oi.Quantity + "\t" +
         oi.LineTotal);
      }
      // Read the subtotal, shipping cost, and total cost.
      Console.WriteLine("\t\t\t\t\t Subtotal\t" + po.SubTotal);
      Console.WriteLine("\t\t\t\t\t Shipping\t" + po.ShipCost); 
      Console.WriteLine("\t\t\t\t\t Total\t\t" + po.TotalCost);
   }
 
   protected void ReadAddress(Address a, string label)
   {
      // Read the fields of the Address object.
      Console.WriteLine(label);
      Console.WriteLine("\t"+ a.Name );
      Console.WriteLine("\t" + a.Line1);
      Console.WriteLine("\t" + a.City);
      Console.WriteLine("\t" + a.State);
      Console.WriteLine("\t" + a.Zip );
      Console.WriteLine();
   }

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

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


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


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


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


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

備註

XML 序列化 (Serialization) 是將物件公用屬性和欄位轉換為儲存或傳輸所用的序列格式 (此處即為 XML) 的程。XML serialization is the process of converting an object's public properties and fields to a serial format (in this case, XML) for storage or transport. 還原序列化會重新建立 XML 輸出從其原始狀態中的物件。Deserialization re-creates the object in its original state from the XML output. 您可以將序列化成資料流或緩衝區中儲存物件狀態的方式。You can think of serialization as a way of saving the state of an object into a stream or buffer. 例如,ASP.NET 會使用XmlSerializer類別來編碼 XML Web 服務訊息。For example, ASP.NET uses the XmlSerializer class to encode XML Web service messages.

您物件中的資料是用程式語言來描述的,該程式語言會建構如類別、欄位、屬性、基本型別 (Primitive Type)、陣列,甚至是以 XmlElementXmlAttribute 物件為格式的內嵌 XML。The data in your objects is described using programming language constructs like classes, fields, properties, primitive types, arrays, and even embedded XML in the form of XmlElement or XmlAttribute objects. 您可以選擇建立您自己的類別、 屬性或使用附註XML 結構描述定義工具 (Xsd.exe)產生根據現有 XML 結構描述定義 (XSD) 文件的類別。You have the option of creating your own classes, annotated with attributes, or using the XML Schema Definition Tool (Xsd.exe) to generate the classes based on an existing XML Schema definition (XSD) document. 如果您有 XML 結構描述時,您可以執行 Xsd.exe 產生一組強型別為結構描述並以符合結構描述時序列化的屬性註解類別。If you have an XML Schema, you can run the Xsd.exe to produce a set of classes that are strongly typed to the schema and annotated with attributes to adhere to the schema when serialized.

物件與 XML 之間傳輸資料需要從 XML 結構描述的程式設計語言建構和程式語言建構的 XML 結構描述的對應。To transfer data between objects and XML requires a mapping from the programming language constructs to XML schema and from the XML schema to the programming language constructs. XmlSerializer和相關的工具,像是 Xsd.exe 提供這兩種技術,同時設計階段與執行階段之間的橋樑。The XmlSerializer and related tools like Xsd.exe provide the bridge between these two technologies at both design time and runtime. 在設計階段,請使用 Xsd.exe,從您的自訂類別產生 XML 結構描述文件 (.xsd) 或產生從指定的結構描述的類別。At design time, use the Xsd.exe to produce an XML schema document (.xsd) from your custom classes or to produce classes from a given schema. 在任一情況下,類別會以屬性註解自訂指示XmlSerializer如何將 XML 結構描述系統和 common language runtime 之間對應。In either case, the classes are annotated with custom attributes to instruct the XmlSerializer how to map between the XML schema system and the common language runtime. 在執行階段類別的執行個體可以序列化指定的結構描述的 XML 文件。At runtime, instances of the classes can be serialized into XML documents that follow the given schema. 同樣地,這些 XML 文件可以還原序列化成執行階段物件。Likewise, these XML documents can be deserialized into runtime objects. 請注意,XML 結構描述是選擇性,不需要在設計階段或執行階段。Note that the XML schema is optional, and not required at design time or runtime.

控制產生的 XMLControlling Generated XML

若要控制所產生的 XML,您可以套用特殊屬性至類別和成員。To control the generated XML, you can apply special attributes to classes and members. 例如,若要指定不同的 XML 項目名稱,套用XmlElementAttribute為公用欄位或屬性,並將ElementName屬性。For example, to specify a different XML element name, apply an XmlElementAttribute to a public field or property, and set the ElementName property. 相似的屬性完整清單,請參閱 < 屬性控制 XML 序列化的For a complete list of similar attributes, see Attributes That Control XML Serialization. 您也可以實作IXmlSerializable介面來控制 XML 輸出。You can also implement the IXmlSerializable interface to control the XML output.

如果產生的 XML 必須符合全球寬協會 (www.w3.org) 文件的第 5 節中,"Simple Object Access Protocol (SOAP) 1.1 」,您必須建構XmlSerializerXmlTypeMappingIf the XML generated must conform to section 5 of the World Wide Consortium (www.w3.org) document, "Simple Object Access Protocol (SOAP) 1.1", you must construct the XmlSerializer with an XmlTypeMapping. 若要進一步控制編碼 SOAP XML,使用 列出的屬性控制編碼 SOAP 序列化的屬性To further control the encoded SOAP XML, use the attributes listed in Attributes That Control Encoded SOAP Serialization.

使用XmlSerializer您可以利用使用強型別類別,但仍有 XML 的彈性。With the XmlSerializer you can take advantage of working with strongly typed classes and still have the flexibility of XML. 使用欄位或屬性的型別XmlElementXmlAttributeXmlNode在強類型類別中,您可以直接將 XML 物件讀取 XML 文件的組件。Using fields or properties of type XmlElement, XmlAttribute or XmlNode in your strongly typed classes, you can read parts of the XML document directly into XML objects.

如果您使用可延伸的 XML 結構描述時,您也可以使用XmlAnyElementAttributeXmlAnyAttributeAttribute序列化和還原序列化的原始結構描述中找不到元素或屬性的屬性。If you work with extensible XML schemas, you can also use the XmlAnyElementAttribute and XmlAnyAttributeAttribute attributes to serialize and deserialize elements or attributes that are not found in the original schema. 若要使用的物件,套用XmlAnyElementAttribute的欄位,傳回的陣列XmlElement物件,或套用XmlAnyAttributeAttribute的欄位,傳回的陣列XmlAttribute物件。To use the objects, apply an XmlAnyElementAttribute to a field that returns an array of XmlElement objects, or apply an XmlAnyAttributeAttribute to a field that returns an array of XmlAttribute objects.

如果屬性或欄位傳回複雜物件 (例如陣列或類別執行個體),XmlSerializer 會將它轉換為主要 XML 文件中的巢狀項目。If a property or field returns a complex object (such as an array or a class instance), the XmlSerializer converts it to an element nested within the main XML document. 例如,下列程式碼中的第一個類別會傳回第二個類別的執行個體。For example, the first class in the following code returns an instance of the second class.

Public Class MyClass  
    Public MyObjectProperty As MyObject  
End Class  

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

序列化,XML 輸出看起來像這樣:The serialized, XML output looks like this:

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

如果結構描述包含的項目,是選擇性的 (minOccurs = '0'),或結構描述會包含預設值,如果您有兩個選項。If a schema includes an element that is optional (minOccurs = '0'), or if the schema includes a default value, you have two options. 其中一個選項是使用System.ComponentModel.DefaultValueAttribute指定預設值,如下列程式碼所示。One option is to use System.ComponentModel.DefaultValueAttribute to specify the default value, as shown in the following code.

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

另一個選項是使用特殊的模式來建立可辨識的布林值欄位XmlSerializer,並套用XmlIgnoreAttribute欄位。Another option is to use a special pattern to create a Boolean field recognized by the XmlSerializer, and to apply the XmlIgnoreAttribute to the field. 模式的形式建立propertyNameSpecifiedThe pattern is created in the form of propertyNameSpecified. 例如,如果沒有名為"MyFirstName 」 也會建立一個名為"MyFirstNameSpecified 」 欄位的欄位,會指示XmlSerializer是否要產生名為"MyFirstName"的 XML 項目。For example, if there is a field named "MyFirstName" you would also create a field named "MyFirstNameSpecified" that instructs the XmlSerializer whether to generate the XML element named "MyFirstName". 這在下列範例中顯示。This is shown in the following example.

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

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

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

覆寫預設的序列化Overriding Default Serialization

您可以藉由建立其中一個適當的屬性,並將它新增至執行個體也覆寫的任何一組物件和其欄位和屬性的序列化XmlAttributes類別。You can also override the serialization of any set of objects and their fields and properties by creating one of the appropriate attributes, and adding it to an instance of the XmlAttributes class. 覆寫序列化以這種方式有兩個用途: 首先,您可以控制和擴充在 DLL 中,找到的物件序列化,即使您沒有存取來源;第二,您可以建立一組可序列化的類別,但是序列化的物件,以多種方式。Overriding serialization in this way has two uses: first, you can control and augment the serialization of objects found in a DLL, even if you do not have access to the source; second, you can create one set of serializable classes, but serialize the objects in multiple ways. 如需詳細資訊,請參閱 < XmlAttributeOverrides 類別和How to:控制在衍生類別的序列化For more details, see the XmlAttributeOverrides class and How to: Control Serialization of Derived Classes.

若要將物件序列化,呼叫Serialize方法。To serialize an object, call the Serialize method. 若要還原序列化物件,呼叫Deserialize方法。To deserialize an object, call the Deserialize method.

若要加入的 XML 文件中的 XML 命名空間,請參閱XmlSerializerNamespacesTo add XML namespaces to an XML document, see XmlSerializerNamespaces.

注意

XmlSerializer提供特殊處理,就可以類別可實作IEnumerableICollectionThe XmlSerializer gives special treatment to classes that implement IEnumerable or ICollection. 實作 IEnumerable 的類別必須實作只取單一參數的公用 Add 方法。A class that implements IEnumerable must implement a public Add method that takes a single parameter. Add方法的參數必須屬於相同的型別傳回的Current屬性傳回的值GetEnumerator,或其中一個該類型的基底。The Add method's parameter must be of the same type as is returned from the Current property on the value returned from GetEnumerator, or one of that type's bases. 類別若實作ICollection(例如CollectionBase) 除了IEnumerable必須具有公用Item編製索引的屬性 (C# 中的索引子),會接受一個整數,而且必須具有公用Count屬於整數類型的屬性。A class that implements ICollection (such as CollectionBase) in addition to IEnumerable must have a public Item indexed property (indexer in C#) that takes an integer, and it must have a public Count property of type integer. 參數Add方法必須是相同的型別,傳回的Item屬性或其中一個該類型的基底。The parameter to the Add method must be the same type as is returned from the Item property, or one of that type's bases. 為類別實作ICollection,要序列化的值擷取自索引Item屬性,不是藉由呼叫GetEnumeratorFor classes that implement ICollection, values to be serialized are retrieved from the indexed Item property, not by calling GetEnumerator.

您必須具有寫入權限的暫存目錄 (如 TEMP 環境變數所定義) 將物件還原序列化。You must have permission to write to the temporary directory (as defined by the TEMP environment variable) to deserialize an object.

以動態方式產生的組件Dynamically Generated Assemblies

若要增加效能,XML 序列化基礎結構會動態產生序列化和還原序列化指定的類型的組件。To increase performance, the XML serialization infrastructure dynamically generates assemblies to serialize and deserialize specified types. 基礎結構會尋找並重複使用這些組件。The infrastructure finds and reuses those assemblies. 只有在使用下列建構函式時,就會發生這種行為:This behavior occurs only when using the following constructors:

XmlSerializer.XmlSerializer(Type)

XmlSerializer.XmlSerializer(Type, String)

如果您使用任何其他建構函式時,多個相同的組件版本產生並永遠不會卸載,而導致記憶體流失和效能不佳。If you use any of the other constructors, multiple versions of the same assembly are generated and never unloaded, which results in a memory leak and poor performance. 最簡單的解決方法是使用其中一個先前所述的兩個建構函式。The easiest solution is to use one of the previously mentioned two constructors. 否則,您必須快取中的組件Hashtable,如下列範例所示。Otherwise, you must cache the assemblies in a Hashtable, as shown in the following example.

Hashtable serializers = new Hashtable();  

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

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

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

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

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

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

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

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

' Use the serializer to serialize or deserialize.

序列化 ArrayList 以及泛型清單Serialization of ArrayList and Generic List

XmlSerializer無法序列化或還原序列化下列:The XmlSerializer cannot serialize or deserialize the following:

列舉的 Unsigned Long 的序列化Serialization of Enumerations of Unsigned Long

XmlSerializer無法具現化序列化列舉型別,如果下列條件成立:列舉型別是不帶正負號長時間的型別 (ulong在C#) 和列舉型別包含任何成員的值大於 9,223,372,036,854,775,807。The XmlSerializer cannot be instantiated to serialize an enumeration if the following conditions are true: The enumeration is of type unsigned long (ulong in C#) and the enumeration contains any member with a value larger than 9,223,372,036,854,775,807. 例如,下列不可序列化。For example, the following cannot be serialized.

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

標記為過時的屬性不會再序列化的物件Objects marked with the Obsolete Attribute no longer serialized

.NET Framework 3.5.NET Framework 3.5 XmlSerializer類別不會再序列化的物件標示為[Obsolete]In the .NET Framework 3.5.NET Framework 3.5 the XmlSerializer class no longer serializes objects that are marked as [Obsolete].

建構函式

XmlSerializer() XmlSerializer() XmlSerializer() XmlSerializer()

初始化 XmlSerializer 類別的新執行個體。Initializes a new instance of the XmlSerializer class.

XmlSerializer(Type) XmlSerializer(Type) XmlSerializer(Type) XmlSerializer(Type)

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件,並可將 XML 文件還原序列化為指定型別的物件。Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into objects of the specified type.

XmlSerializer(Type, String) XmlSerializer(Type, String) XmlSerializer(Type, String) XmlSerializer(Type, String)

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件,並可將 XML 文件還原序列化為指定型別的物件。Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into objects of the specified type. 指定所有 XML 項目的預設命名空間。Specifies the default namespace for all the XML elements.

XmlSerializer(Type, Type[]) XmlSerializer(Type, Type[]) XmlSerializer(Type, Type[]) XmlSerializer(Type, Type[])

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件,並可將 XML 文件還原序列化為指定型別的物件。Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into object of a specified type. 如果屬性或欄位傳回陣列,extraTypes 參數就會指定可插入陣列的物件。If a property or field returns an array, the extraTypes parameter specifies objects that can be inserted into the array.

XmlSerializer(Type, XmlAttributeOverrides) XmlSerializer(Type, XmlAttributeOverrides) XmlSerializer(Type, XmlAttributeOverrides) XmlSerializer(Type, XmlAttributeOverrides)

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件,並可將 XML 文件還原序列化為指定型別的物件。Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into objects of the specified type. 每個要序列化的物件本身會包含類別執行個體,這個多載可以其他類別覆寫。Each object to be serialized can itself contain instances of classes, which this overload can override with other classes.

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

初始化 XmlSerializer 類別的新執行個體,該類別可將 Object 型別的物件序列化為 XML 文件執行個體,並可將 XML 文件執行個體還原序列化為 Object 型別的物件。Initializes a new instance of the XmlSerializer class that can serialize objects of type Object into XML document instances, and deserialize XML document instances into objects of type Object. 每個要序列化的物件本身都可包含類別的執行個體,這個多載會使用其他類別對其進行覆寫。Each object to be serialized can itself contain instances of classes, which this overload overrides with other classes. 這個多載也會指定所有 XML 項目的預設命名空間,以及要做為 XML 根項目的類別。This overload also specifies the default namespace for all the XML elements and the class to use as the XML root element.

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

初始化 XmlSerializer 類別的新執行個體,該類別可將 Object 型別的物件序列化為 XML 文件執行個體,並可將 XML 文件執行個體還原序列化為 Object 型別的物件。Initializes a new instance of the XmlSerializer class that can serialize objects of type Object into XML document instances, and deserialize XML document instances into objects of type Object. 每個要序列化的物件本身都可包含類別的執行個體,這個多載會使用其他類別對其進行覆寫。Each object to be serialized can itself contain instances of classes, which this overload overrides with other classes. 這個多載也會指定所有 XML 項目的預設命名空間,以及要做為 XML 根項目的類別。This overload also specifies the default namespace for all the XML elements and the class to use as the XML root element.

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

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件執行個體,並可將 XML 文件執行個體還原序列化為指定型別的物件。Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML document instances, and deserialize XML document instances into objects of the specified type. 這個多載可讓您提供序列化或還原序列化作業期間遇到的其他型別,以及所有 XML 項目的預設命名空間、用做 XML 根項目的類別及其位置,和存取所需的認證。This overload allows you to supply other types that can be encountered during a serialization or deserialization operation, as well as a default namespace for all XML elements, the class to use as the XML root element, its location, and credentials required for access.

XmlSerializer(Type, XmlRootAttribute) XmlSerializer(Type, XmlRootAttribute) XmlSerializer(Type, XmlRootAttribute) XmlSerializer(Type, XmlRootAttribute)

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件,並可將 XML 文件還原序列化為指定型別的物件。Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize an XML document into object of the specified type. 它還指定做為 XML 根項目的類別。It also specifies the class to use as the XML root element.

XmlSerializer(XmlTypeMapping) XmlSerializer(XmlTypeMapping) XmlSerializer(XmlTypeMapping) XmlSerializer(XmlTypeMapping)

使用將一個型別對應到另一個型別的物件,初始化 XmlSerializer 類別的執行個體。Initializes an instance of the XmlSerializer class using an object that maps one type to another.

方法

CanDeserialize(XmlReader) CanDeserialize(XmlReader) CanDeserialize(XmlReader) CanDeserialize(XmlReader)

取得值,指出這個 XmlSerializer 是否可以還原序列化指定的 XML 文件。Gets a value that indicates whether this XmlSerializer can deserialize a specified XML document.

CreateReader() CreateReader() CreateReader() CreateReader()

傳回物件,該物件用於讀取要序列化的 XML 文件。Returns an object used to read the XML document to be serialized.

CreateWriter() CreateWriter() CreateWriter() CreateWriter()

在衍生類別中覆寫時,傳回用於序列化物件的寫入器。When overridden in a derived class, returns a writer used to serialize the object.

Deserialize(Stream) Deserialize(Stream) Deserialize(Stream) Deserialize(Stream)

還原序列化指定 Stream 所包含的 XML 文件。Deserializes the XML document contained by the specified Stream.

Deserialize(TextReader) Deserialize(TextReader) Deserialize(TextReader) Deserialize(TextReader)

還原序列化指定 TextReader 所包含的 XML 文件。Deserializes the XML document contained by the specified TextReader.

Deserialize(XmlReader) Deserialize(XmlReader) Deserialize(XmlReader) Deserialize(XmlReader)

還原序列化指定 XmlReader 所包含的 XML 文件。Deserializes the XML document contained by the specified XmlReader.

Deserialize(XmlReader, String) Deserialize(XmlReader, String) Deserialize(XmlReader, String) Deserialize(XmlReader, String)

還原序列化指定 XmlReader 和編碼樣式所包含的 XML 文件。Deserializes the XML document contained by the specified XmlReader and encoding style.

Deserialize(XmlReader, String, XmlDeserializationEvents) Deserialize(XmlReader, String, XmlDeserializationEvents) Deserialize(XmlReader, String, XmlDeserializationEvents) Deserialize(XmlReader, String, XmlDeserializationEvents)

使用指定 XmlReader 包含的資料,還原序列化物件。Deserializes the object using the data contained by the specified XmlReader.

Deserialize(XmlReader, XmlDeserializationEvents) Deserialize(XmlReader, XmlDeserializationEvents) Deserialize(XmlReader, XmlDeserializationEvents) Deserialize(XmlReader, XmlDeserializationEvents)

還原序列化指定 XmlReader 包含的 XML 文件,並允許覆寫還原序列化期間發生的事件。Deserializes an XML document contained by the specified XmlReader and allows the overriding of events that occur during deserialization.

Deserialize(XmlSerializationReader) Deserialize(XmlSerializationReader) Deserialize(XmlSerializationReader) Deserialize(XmlSerializationReader)

還原序列化指定 XmlSerializationReader 所包含的 XML 文件。Deserializes the XML document contained by the specified XmlSerializationReader.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
FromMappings(XmlMapping[]) FromMappings(XmlMapping[]) FromMappings(XmlMapping[]) FromMappings(XmlMapping[])

傳回建立自 XmlSerializer 物件陣列的 XmlTypeMapping 物件陣列。Returns an array of XmlSerializer objects created from an array of XmlTypeMapping objects.

FromMappings(XmlMapping[], Evidence) FromMappings(XmlMapping[], Evidence) FromMappings(XmlMapping[], Evidence) FromMappings(XmlMapping[], Evidence)

傳回 XmlSerializer 類別的執行個體,該執行個體建立自一個 XML 型別至另一個 XML 型別的對應。Returns an instance of the XmlSerializer class created from mappings of one XML type to another.

FromMappings(XmlMapping[], Type) FromMappings(XmlMapping[], Type) FromMappings(XmlMapping[], Type) FromMappings(XmlMapping[], Type)

傳回指定對應的 XmlSerializer 類別執行個體。Returns an instance of the XmlSerializer class from the specified mappings.

FromTypes(Type[]) FromTypes(Type[]) FromTypes(Type[]) FromTypes(Type[])

傳回由型別陣列建立的 XmlSerializer 物件的陣列。Returns an array of XmlSerializer objects created from an array of types.

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

使用指定的對應傳回組件,該組件包含自訂序列化程式,用於序列化或還原序列化指定的型別。Returns an assembly that contains custom-made serializers used to serialize or deserialize the specified type or types, using the specified mappings.

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

使用指定的對應、編譯器設定和選項傳回組件,該組件包含自訂序列化程式,用於序列化或還原序列化指定的型別。Returns an assembly that contains custom-made serializers used to serialize or deserialize the specified type or types, using the specified mappings and compiler settings and options.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
GetXmlSerializerAssemblyName(Type) GetXmlSerializerAssemblyName(Type) GetXmlSerializerAssemblyName(Type) GetXmlSerializerAssemblyName(Type)

傳回組件名稱,該組件包含一個或多個 XmlSerializer 版本,是為序列化或還原序列化特定型別建立的。Returns the name of the assembly that contains one or more versions of the XmlSerializer especially created to serialize or deserialize the specified type.

GetXmlSerializerAssemblyName(Type, String) GetXmlSerializerAssemblyName(Type, String) GetXmlSerializerAssemblyName(Type, String) GetXmlSerializerAssemblyName(Type, String)

傳回組件名稱,該組件包含指定命名空間中指定型別的序列化程式。Returns the name of the assembly that contains the serializer for the specified type in the specified namespace.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
Serialize(Object, XmlSerializationWriter) Serialize(Object, XmlSerializationWriter) Serialize(Object, XmlSerializationWriter) Serialize(Object, XmlSerializationWriter)

序列化指定的 Object,並使用指定的 XmlSerializationWriter 將 XML 文件寫入檔案。Serializes the specified Object and writes the XML document to a file using the specified XmlSerializationWriter.

Serialize(Stream, Object) Serialize(Stream, Object) Serialize(Stream, Object) 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) Serialize(Stream, Object, XmlSerializerNamespaces) Serialize(Stream, Object, XmlSerializerNamespaces) 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(TextWriter, Object) Serialize(TextWriter, Object) Serialize(TextWriter, Object) Serialize(TextWriter, Object)

序列化指定的 Object,並使用指定的 TextWriter 將 XML 文件寫入檔案。Serializes the specified Object and writes the XML document to a file using the specified TextWriter.

Serialize(TextWriter, Object, XmlSerializerNamespaces) Serialize(TextWriter, Object, XmlSerializerNamespaces) Serialize(TextWriter, Object, XmlSerializerNamespaces) 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(XmlWriter, Object) Serialize(XmlWriter, Object) Serialize(XmlWriter, Object) 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) Serialize(XmlWriter, Object, XmlSerializerNamespaces) Serialize(XmlWriter, Object, XmlSerializerNamespaces) 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(XmlWriter, Object, XmlSerializerNamespaces, String) Serialize(XmlWriter, Object, XmlSerializerNamespaces, String) Serialize(XmlWriter, Object, XmlSerializerNamespaces, String) 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, String, String) Serialize(XmlWriter, Object, XmlSerializerNamespaces, String, String) Serialize(XmlWriter, Object, XmlSerializerNamespaces, String, String) Serialize(XmlWriter, Object, XmlSerializerNamespaces, String, String)

序列化指定的 Object,並使用指定的 XmlWriter、XML 命名空間和編碼方式,將 XML 文件寫入檔案。Serializes the specified Object and writes the XML document to a file using the specified XmlWriter, XML namespaces, and encoding.

ToString() ToString() ToString() ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)

事件

UnknownAttribute UnknownAttribute UnknownAttribute UnknownAttribute

當還原序列化期間,XmlSerializer 遭遇未知型別的 XML 屬性時發生。Occurs when the XmlSerializer encounters an XML attribute of unknown type during deserialization.

UnknownElement UnknownElement UnknownElement UnknownElement

當還原序列化期間,XmlSerializer 遭遇未知型別的 XML 項目時發生。Occurs when the XmlSerializer encounters an XML element of unknown type during deserialization.

UnknownNode UnknownNode UnknownNode UnknownNode

當還原序列化期間,XmlSerializer 遭遇未知型別的 XML 節點時發生。Occurs when the XmlSerializer encounters an XML node of unknown type during deserialization.

UnreferencedObject UnreferencedObject UnreferencedObject UnreferencedObject

在 SOAP 編碼的 XML 資料流還原序列化期間,XmlSerializer 遇到未使用 (未參考) 的可辨認型別時發生。Occurs during deserialization of a SOAP-encoded XML stream, when the XmlSerializer encounters a recognized type that is not used or is unreferenced.

適用於

執行緒安全性

此型別具備執行緒安全。This type is thread safe.

另請參閱