XmlSerializer 類別

定義

將物件序列化與反序列化,進出 XML 文件。 這 XmlSerializer 讓你能控制物件如何編碼成 XML。

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

範例

以下範例包含兩個主要類別: PurchaseOrderTest。 該 PurchaseOrder 類別包含單一購買的資訊。 這個 Test 類別包含建立採購單的方法,以及讀取已建立的採購單的方法。

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

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

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

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

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

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

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

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

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

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

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

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

      // A FileStream is needed to read the XML document.
      FileStream fs = new FileStream(filename, FileMode.Open);
      // Declare an object variable of the type to be deserialized.
      PurchaseOrder po;
      /* Use the Deserialize method to restore the object's state with
      data from the XML document. */
      po = (PurchaseOrder) serializer.Deserialize(fs);
      // Read the order date.
      Console.WriteLine ("OrderDate: " + po.OrderDate);

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

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

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

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

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


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


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


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

備註

XML 串行化是將物件的公用屬性和欄位轉換成儲存或傳輸的序列格式(在此案例中為 XML)的程式。 反序列化會從 XML 輸出中重新建立物件的原始狀態。 您可以將串行化視為將物件狀態儲存至數據流或緩衝區的方式。 例如,ASP.NET 使用 類別 XmlSerializer 來編碼 XML Web 服務訊息。

對象中的數據是利用程式設計語言的構造來描述,例如類別、欄位、屬性、基本類型、陣列,甚至是以XmlElementXmlAttribute物件形式內嵌的 XML。 您可以選擇建立自己的類別、以屬性標註,或使用 XML 架構定義工具 (Xsd.exe) 根據現有的 XML 架構定義 ( XSD) 檔案產生類別。 如果您有一個 XML 架構,您可以執行 Xsd.exe,以生成一組與該架構強型別匹配的類別,並在序列化時加上符合架構的屬性註解。

若要在物件與 XML 之間傳輸數據,需要將程式語言結構映射到 XML 架構,並將 XML 架構映射回程式語言結構。 XmlSerializer 及 Xsd.exe 等相關工具在設計時間和執行時間提供這兩種技術之間的橋樑。 在設計時間,使用 Xsd.exe 從自定義類別產生 XML 架構檔 (.xsd),或從指定的架構產生類別。 不論是哪一種情況,類別都以自定義屬性標註,以指示 XmlSerializer 如何在 XML 架構系統與 Common Language Runtime 之間對應。 在運行時間,類別的實例可以串行化為遵循指定架構的 XML 檔。 同樣地,這些 XML 檔也可以反序列化為運行時間物件。 請注意,XML 架構是選擇性的,在設計時間或運行時間不需要。

控件產生的 XML

若要控制產生的 XML,您可以將特殊屬性套用至類別和成員。 例如,若要指定不同的 XML 項目名稱,請將 套用 XmlElementAttribute 至公用字段或屬性,並設定 ElementName 屬性。 如需類似屬性的完整清單,請參閱 控制 XML 串行化的屬性。 您也可以實作 IXmlSerializable 介面來控制 XML 輸出。

如果產生的 XML 必須符合萬維網協會文件的第 5 節,簡單物件存取協定(SOAP)1.1,您必須使用 XmlSerializer來建構 XmlTypeMapping。 若要進一步控制編碼的SOAP XML,請使用 控制編碼SOAP串行化之屬性中列出的屬性。

使用XmlSerializer,您可以充分利用強型別類別的優勢,同時仍然享有 XML 的彈性。 在您的強類型化類別中,使用類型為 XmlElementXmlAttributeXmlNode 的欄位或屬性,可以將 XML 檔的一部分直接讀入 XML 物件。

如果您使用可延伸的 XML 架構,也可以使用 XmlAnyElementAttributeXmlAnyAttributeAttribute 屬性來序列化和反序列化原始架構中找不到的元素或屬性。 若要使用 物件,請將 套用 XmlAnyElementAttribute 至傳回物件陣列的 XmlElement 欄位,或將套用 XmlAnyAttributeAttribute 至傳回物件陣列的 XmlAttribute 欄位。

如果屬性或欄位傳回複雜物件(例如陣列或類別實例),XmlSerializer 會將它轉換成巢狀在主要 XML 檔中的元素。 例如,下列程式代碼中的第一個類別會傳回第二個類別的實例。

Public Class MyClass
    Public MyObjectProperty As MyObject
End Class

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

序列化的 XML 輸出如下所示:

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

如果架構包含選擇性的專案(minOccurs = '0'),或者如果架構包含預設值,則您有兩個選項。 其中一個選項是使用 System.ComponentModel.DefaultValueAttribute 來指定預設值,如下列程式代碼所示。

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

另一個選項是使用特殊模式來建立由 XmlSerializer 辨識的布爾值欄位,並將 XmlIgnoreAttribute 套用至該欄位。 模式會以propertyNameSpecified的形式創建。 例如,如果有名為 「MyFirstName」 的欄位,您也會建立名為 「MyFirstNameSpecified」 的字段,指示 XmlSerializer 是否要產生名為 “MyFirstName” 的 XML 元素。 下列範例會顯示這一點。

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

覆寫預設序列化

** 您也可以藉由建立適當的屬性,並將其添加到 XmlAttributes 類別的實例中,以覆寫任何一組物件及其欄位和屬性的序列化。 以這種方式覆寫串行化有兩個用途:第一,即使您沒有來源的存取權,您也可以控制及增強 DLL 中找到的物件串行化;第二,您可以建立一組可串行化的類別,但以多種方式串行化物件。 如需詳細資訊,請參閱 XmlAttributeOverrides 類別和 如何:控制衍生類別的串行化

若要串行化物件,請呼叫 Serialize 方法。 若要還原串行化物件,請呼叫 Deserialize 方法。

若要將 XML 命名空間新增至 XML 檔,請參閱 XmlSerializerNamespaces

Note

XmlSerializer 為實作 IEnumerableICollection 的類別提供特殊處理。 實作的 IEnumerable 類別必須實作採用單一參數的公用 Add 方法。 方法 Add 的參數類型必須與從 Current 所傳回的值上的GetEnumerator 屬性所傳回的類型相同,或者是該類型的其中一個基底類型。 實作 ICollection(例如 CollectionBase)並且包括 IEnumerable 的類別必須具有一個接受整數的公用Item索引屬性(在 C# 中稱為 indexer),而且還必須具有一個整數類型的公用Count屬性。 方法的參數 Add 必須與 從 Item 屬性傳回的 型別相同,或是該型別的其中一個基底。 要串行化的值是從實作 ICollection 的類別中的索引 Item 屬性中取得,而不是透過呼叫 GetEnumerator

您必須具有寫入暫存目錄的許可權(如 TEMP 環境變數所定義),才能還原串行化物件。

動態生成的組件

為了提升效能,XML 序列化架構會動態生成組件,以序列化和還原序列化指定的型別。 基礎結構會尋找並重複使用這些元件。 只有在使用下列建構函式時,才會發生此行為:

XmlSerializer.XmlSerializer(Type)

XmlSerializer.XmlSerializer(Type, String)

如果您使用任何其他建構函式,就會產生多個相同元件的版本,而且永遠不會卸除,這會導致記憶體流失和效能不佳。 最簡單的解決方案是使用先前提及的兩個建構函式之一。 否則,您必須在Hashtable中快取元件,如下列範例所示。

Hashtable serializers = new Hashtable();

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

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

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

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

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

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

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

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

' Use the serializer to serialize or deserialize.

ArrayList 和泛型清單的串行化

XmlSerializer無法序列化或反序列化下列項目:

無符號 Long 列舉的序列化

XmlSerializer如果下列條件成立,則無法具現化 來串行化列舉:列舉型別為未帶正負號的long (ulong在 C# 中為 ),而且列舉包含任何大於9,223,372,036,854,775,807 的成員。 例如,下列內容無法被序列化。

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

過時的類型

XmlSerializer 類別不會序列化標記為 [Obsolete]的物件。

建構函式

名稱 Description
XmlSerializer()

初始化 XmlSerializer 類別的新執行個體。

XmlSerializer(Type, String)

初始化該類別的新實例,該實例 XmlSerializer 能將指定類型的物件序列化為 XML 文件,並將 XML 文件反序列化為指定類型的物件。 指定所有 XML 元素的預設命名空間。

XmlSerializer(Type, Type[])

初始化一個新的類別實例,該實例 XmlSerializer 能將指定類型的物件序列化為 XML 文件,並將 XML 文件反序列化為指定類型的物件。 如果某個屬性或欄位回傳陣列,該 extraTypes 參數會指定可以插入到陣列中的物件。

XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String, Evidence)
已淘汰.

初始化該類別的新實例,該實例 XmlSerializer 能將指定類型的物件序列化為 XML 文件實例,並將 XML 文件實例反序列化為指定類型的物件。 這種過載讓你能提供序列化或反序列化操作中可能遇到的其他類型,以及所有 XML 元素的預設命名空間、用作 XML 根元素的類別、其位置,以及存取所需的憑證。

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

初始化該類別的新實例,該實例 XmlSerializer 能將 類型的 Object 物件序列化為 XML 文件實例,並將 XML 文件實例反序列化為型別 Object為 的物件。 每個待序列化的物件本身可以包含類別的實例,這種過載會用其他類別覆蓋這些類別。 此過載同時指定所有 XML 元素的預設命名空間,以及作為 XML 根元素的類別。

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

初始化該類別的新實例,該實例 XmlSerializer 能將 類型的 Object 物件序列化為 XML 文件實例,並將 XML 文件實例反序列化為型別 Object為 的物件。 每個待序列化的物件本身可以包含類別的實例,這種過載會用其他類別覆蓋這些類別。 此過載同時指定所有 XML 元素的預設命名空間,以及作為 XML 根元素的類別。

XmlSerializer(Type, XmlAttributeOverrides)

初始化該類別的新實例,該實例 XmlSerializer 能將指定類型的物件序列化為 XML 文件,並將 XML 文件反序列化為指定類型的物件。 每個待序列化的物件本身可以包含類別的實例,這種過載可以用其他類別覆蓋這些類別。

XmlSerializer(Type, XmlRootAttribute)

初始化該類別的新實例,該實例 XmlSerializer 能將指定類型的物件序列化為 XML 文件,並將 XML 文件反序列化為指定類型的物件。 它也指定了作為 XML 根元素的類別。

XmlSerializer(Type)

初始化該類別的新實例,該實例 XmlSerializer 能將指定類型的物件序列化為 XML 文件,並將 XML 文件反序列化為指定類型的物件。

XmlSerializer(XmlTypeMapping)

使用一個將一個類型映射到另一個類型的物件來初始化該 XmlSerializer 類別的實例。

方法

名稱 Description
CanDeserialize(XmlReader)

會取得一個值,指示是否 XmlSerializer 能反序列化指定的 XML 文件。

CreateReader()

回傳一個用於讀取待序列化 XML 文件的物件。

CreateWriter()

當在衍生類別中覆寫時,會回傳一個用於序列化物件的寫入者。

Deserialize(Stream)

將指定的 StreamXML 文件反序列化。

Deserialize(TextReader)

將指定的 TextReaderXML 文件反序列化。

Deserialize(XmlReader, String, XmlDeserializationEvents)

利用指定 XmlReader資料將物件反序列化。

Deserialize(XmlReader, String)

反序列化由指定 XmlReader 與編碼風格所包含的 XML 文件。

Deserialize(XmlReader, XmlDeserializationEvents)

反序列化由指定 XmlReader 文件所包含的 XML 文件,並允許覆蓋反序列化過程中發生的事件。

Deserialize(XmlReader)

將指定的 XmlReaderXML 文件反序列化。

Deserialize(XmlSerializationReader)

將指定的 XmlSerializationReaderXML 文件反序列化。

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
FromMappings(XmlMapping[], Evidence)
已淘汰.

回傳由一種 XML 類型映射到另一種 XML 類型所建立的 XmlSerializer 類別實例。

FromMappings(XmlMapping[], Type)

從指定的映射中回傳該 XmlSerializer 類別的實例。

FromMappings(XmlMapping[])

回傳由一組XmlSerializer物件陣列建立的物件陣列XmlTypeMapping

FromTypes(Type[])

回傳由多種類型陣列建立的物件陣列 XmlSerializer

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

回傳一個組合語言,內含自訂序列化器,用於使用指定的映射及編譯器設定與選項,序列化或反序列化指定型別。

GenerateSerializer(Type[], XmlMapping[])

回傳一個包含自訂序列化器的組件,該序列器用於使用指定的映射方式序列化或反序列化指定型別。

GetHashCode()

做為預設哈希函式。

(繼承來源 Object)
GetType()

取得目前實例的 Type

(繼承來源 Object)
GetXmlSerializerAssemblyName(Type, String)

回傳包含指定命名空間中指定型別序列化器的組件名稱。

GetXmlSerializerAssemblyName(Type)

回傳包含一個或多個 XmlSerializer 特別用於序列化或反序列化的版本的組合名稱。

MemberwiseClone()

建立目前 Object的淺層複本。

(繼承來源 Object)
Serialize(Object, XmlSerializationWriter)

序列化指定的 Object 文件,並使用指定的 XmlSerializationWriter寫入檔案。

Serialize(Stream, Object, XmlSerializerNamespaces)

序列化指定的 Object 文件,並利用指定的名稱 Stream 空間撰寫 XML 文件到檔案。

Serialize(Stream, Object)

序列化指定的 Object 文件,並使用指定的 Stream寫入檔案。

Serialize(TextWriter, Object, XmlSerializerNamespaces)

序列化指定的 Object 文件,並使用指定的 TextWriter 名稱空間將 XML 文件寫入檔案,並參考指定的命名空間。

Serialize(TextWriter, Object)

序列化指定的 Object 文件,並使用指定的 TextWriter寫入檔案。

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

序列化指定的 Object 文件,並利用指定的 XmlWriter、 XML 命名空間及編碼將 XML 文件寫入檔案。

Serialize(XmlWriter, Object, XmlSerializerNamespaces, String)

序列化指定物件,並使用指定 XmlWriter 內容將 XML 文件寫入檔案,並參考指定的命名空間與編碼樣式。

Serialize(XmlWriter, Object, XmlSerializerNamespaces)

序列化指定的 Object 文件,並使用指定的 XmlWriter 名稱空間將 XML 文件寫入檔案,並參考指定的命名空間。

Serialize(XmlWriter, Object)

序列化指定的 Object 文件,並使用指定的 XmlWriter寫入檔案。

ToString()

傳回表示目前 物件的字串。

(繼承來源 Object)

事件

名稱 Description
UnknownAttribute

當在 XmlSerializer 反序列化過程中遇到未知類型的 XML 屬性時,會發生這種情況。

UnknownElement

當在 XmlSerializer 反序列化過程中遇到未知類型的 XML 元素時,會發生這種情況。

UnknownNode

當在 XmlSerializer 反序列化過程中遇到未知類型的 XML 節點時,會發生這種情況。

UnreferencedObject

發生在 SOAP 編碼的 XML 串流反序列化時,當遇到 XmlSerializer 未被使用或未被引用的已識別型態時。

適用於

執行緒安全性

此類型是安全線程。

另請參閱