XmlSerializer 類別

定義

將物件序列化為 XML 文件,以及從 XML 文件將物件還原序列化。 XmlSerializer 可讓您控制如何將物件編碼為 XML。

C#
public class XmlSerializer
繼承
XmlSerializer

範例

下列範例包含兩個主要類別: PurchaseOrderTest。 類別 PurchaseOrder 包含單一購買的相關信息。 類別 Test 包含建立採購單的方法,以及讀取所建立的採購單。

C#
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 + "'");
   }
}

備註

如需此 API 的詳細資訊,請參閱 XmlSerializer 的補充 API 備註

建構函式

XmlSerializer()

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

XmlSerializer(Type)

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件,並可將 XML 文件還原序列化為指定型別的物件。

XmlSerializer(Type, String)

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件,並可將 XML 文件還原序列化為指定型別的物件。 指定所有 XML 項目的預設命名空間。

XmlSerializer(Type, Type[])

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件,並可將 XML 文件還原序列化為指定型別的物件。 如果屬性或欄位傳回陣列,extraTypes 參數就會指定可插入陣列的物件。

XmlSerializer(Type, XmlAttributeOverrides)

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件,並可將 XML 文件還原序列化為指定型別的物件。 每個要序列化的物件本身會包含類別執行個體,這個多載可以其他類別覆寫。

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

初始化 XmlSerializer 類別的新執行個體,該類別可將 Object 型別的物件序列化為 XML 文件執行個體,並可將 XML 文件執行個體還原序列化為 Object 型別的物件。 每個要序列化的物件本身都可包含類別的執行個體,這個多載會使用其他類別對其進行覆寫。 這個多載也會指定所有 XML 項目的預設命名空間,以及要做為 XML 根項目的類別。

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

初始化 XmlSerializer 類別的新執行個體,該類別可將 Object 型別的物件序列化為 XML 文件執行個體,並可將 XML 文件執行個體還原序列化為 Object 型別的物件。 每個要序列化的物件本身都可包含類別的執行個體,這個多載會使用其他類別對其進行覆寫。 這個多載也會指定所有 XML 項目的預設命名空間,以及要做為 XML 根項目的類別。

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

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件執行個體,並可將 XML 文件執行個體還原序列化為指定型別的物件。 這個多載可讓您提供序列化或還原序列化作業期間遇到的其他型別,以及所有 XML 項目的預設命名空間、用做 XML 根項目的類別及其位置,和存取所需的認證。

XmlSerializer(Type, XmlRootAttribute)

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件,並可將 XML 文件還原序列化為指定型別的物件。 它還指定做為 XML 根項目的類別。

XmlSerializer(XmlTypeMapping)

使用將一個型別對應到另一個型別的物件,初始化 XmlSerializer 類別的執行個體。

方法

CanDeserialize(XmlReader)

取得值,指出這個 XmlSerializer 是否可以還原序列化指定的 XML 文件。

CreateReader()

傳回物件,該物件用於讀取要序列化的 XML 文件。

CreateWriter()

在衍生類別中覆寫時,傳回用於序列化物件的寫入器。

Deserialize(Stream)

還原序列化指定 Stream 所包含的 XML 文件。

Deserialize(TextReader)

還原序列化指定 TextReader 所包含的 XML 文件。

Deserialize(XmlReader)

還原序列化指定 XmlReader 所包含的 XML 文件。

Deserialize(XmlReader, String)

還原序列化指定 XmlReader 和編碼樣式所包含的 XML 文件。

Deserialize(XmlReader, String, XmlDeserializationEvents)

使用指定 XmlReader 包含的資料,還原序列化物件。

Deserialize(XmlReader, XmlDeserializationEvents)

還原序列化指定 XmlReader 包含的 XML 文件,並允許覆寫還原序列化期間發生的事件。

Deserialize(XmlSerializationReader)

還原序列化指定 XmlSerializationReader 所包含的 XML 文件。

Equals(Object)

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

(繼承來源 Object)
FromMappings(XmlMapping[])

傳回建立自 XmlSerializer 物件陣列的 XmlTypeMapping 物件陣列。

FromMappings(XmlMapping[], Evidence)
已淘汰.

傳回 XmlSerializer 類別的執行個體,該執行個體建立自一個 XML 型別至另一個 XML 型別的對應。

FromMappings(XmlMapping[], Type)

傳回指定對應的 XmlSerializer 類別執行個體。

FromTypes(Type[])

傳回由型別陣列建立的 XmlSerializer 物件的陣列。

GenerateSerializer(Type[], XmlMapping[])

使用指定的對應傳回組件,該組件包含自訂序列化程式,用於序列化或還原序列化指定的型別。

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

使用指定的對應、編譯器設定和選項傳回組件,該組件包含自訂序列化程式,用於序列化或還原序列化指定的型別。

GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetType()

取得目前執行個體的 Type

(繼承來源 Object)
GetXmlSerializerAssemblyName(Type)

傳回組件名稱,該組件包含一個或多個 XmlSerializer 版本,是為序列化或還原序列化特定型別建立的。

GetXmlSerializerAssemblyName(Type, String)

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

MemberwiseClone()

建立目前 Object 的淺層複製。

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

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

Serialize(Stream, Object)

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

Serialize(Stream, Object, XmlSerializerNamespaces)

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

Serialize(TextWriter, Object)

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

Serialize(TextWriter, Object, XmlSerializerNamespaces)

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

Serialize(XmlWriter, Object)

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

Serialize(XmlWriter, Object, XmlSerializerNamespaces)

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

Serialize(XmlWriter, Object, XmlSerializerNamespaces, String)

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

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

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

ToString()

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

(繼承來源 Object)

事件

UnknownAttribute

當還原序列化期間,XmlSerializer 遭遇未知型別的 XML 屬性時發生。

UnknownElement

當還原序列化期間,XmlSerializer 遭遇未知型別的 XML 項目時發生。

UnknownNode

當還原序列化期間,XmlSerializer 遭遇未知型別的 XML 節點時發生。

UnreferencedObject

在 SOAP 編碼的 XML 資料流還原序列化期間,XmlSerializer 遇到未使用 (未參考) 的可辨認型別時發生。

適用於

產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0

執行緒安全性

此型別具備執行緒安全。

另請參閱