XML 序列化簡介Introducing XML Serialization

序列化是將物件轉換成可輕易傳輸之形式的程序。Serialization is the process of converting an object into a form that can be readily transported. 例如,您可序列化物件並透過網際網路以 HTTP 在用戶端與伺服器之間傳輸。For example, you can serialize an object and transport it over the Internet using HTTP between a client and a server. 另一方面,還原序列化從資料流重建物件。On the other end, deserialization reconstructs the object from the stream.

XML 序列化僅對物件的公用欄位及屬性值序列化至 XML 資料流。XML serialization serializes only the public fields and property values of an object into an XML stream. XML 序列化不包含型別資訊。XML serialization does not include type information. 例如,若您在 Library 命名空間中有 Book 物件,不保證它能還原序列化成為相同類型的物件。For example, if you have a Book object that exists in the Library namespace, there is no guarantee that it is deserialized into an object of the same type.

注意

XML 序列化不會轉換方法、索引子、私用欄位或唯讀屬性 (唯讀集合除外)。XML serialization does not convert methods, indexers, private fields, or read-only properties (except read-only collections). 若要序列化物件的所有欄位與屬性,無論是公用或私用,請使用 DataContractSerializer,而非 XML 序列化。To serialize all an object's fields and properties, both public and private, use the DataContractSerializer instead of XML serialization.

XML 序列化的核心類別為 XmlSerializer 類別,此類別中最重要的方法為序列化還原序列化方法。The central class in XML serialization is the XmlSerializer class, and the most important methods in this class are the Serialize and Deserialize methods. XmlSerializer 建立 C# 檔案並將它們編譯成為 .dll 檔案以執行此序列化。The XmlSerializer creates C# files and compiles them into .dll files to perform this serialization. 在 .NET Framework 2.0 中,XML 序列化程式產生器工具 (Sgen.exe) 的設計是用來預先產生要與您應用程式一起部署的這些序列化組件,並改善啟動效能。In .NET Framework 2.0, the XML Serializer Generator Tool (Sgen.exe) is designed to generate these serialization assemblies in advance to be deployed with your application and improve startup performance. 產生的 XML 資料流XmlSerializer World Wide Web Consortium (W3C) 符合XML 結構描述定義語言 (XSD) 1.0 建議The XML stream generated by the XmlSerializer is compliant with the World Wide Web Consortium (W3C) XML Schema definition language (XSD) 1.0 recommendation. 此外,產生的資料型別是符合規範與文件標題為 「 XML 結構描述第 2 部分:資料類型。 」Furthermore, the data types generated are compliant with the document titled "XML Schema Part 2: Datatypes."

您物件中的資料是用程式語言來描述的,該程式語言會建構如類別、欄位、屬性、基本類型、陣列,甚至是以 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 結構描述定義工具來依據現有 XML 結構描述產生類別。You have the option of creating your own classes, annotated with attributes, or using the XML Schema Definition tool to generate the classes based on an existing XML Schema.

如果有 XML 結構描述,您可以執行 XML 結構描述定義工具來產生類別集,這些類別集是結構描述的強型別 (Strongly Typed),而且以屬性註解。If you have an XML Schema, you can run the XML Schema Definition tool to produce a set of classes that are strongly typed to the schema and annotated with attributes. 當如此類別的執行個體序列化時,產生的 XML 符合 XML 結構描述。When an instance of such a class is serialized, the generated XML adheres to the XML Schema. 隨著這種類別的提供,您可以根據操作簡易的物件模型進行程式設計,同時能確保產生的 XML 符合 XML 結構描述。Provided with such a class, you can program against an easily manipulated object model while being assured that the generated XML conforms to the XML schema. 這是在 .NET Framework 使用其他類別的替代方法,就像是 XmlReaderXmlWriter 類別,用來剖析與撰寫 XML 資料流。This is an alternative to using other classes in the .NET Framework, such as the XmlReader and XmlWriter classes, to parse and write an XML stream. 如需詳細資訊,請參閱 XML 文件和資料For more information, see XML Documents and Data. 這些類別讓您能剖析所有 XML 資料流。These classes allow you to parse any XML stream. 相反地,當預期 XML 資料流符合已知 XML 結構描述時,請使用 XmlSerializerIn contrast, use the XmlSerializer when the XML stream is expected to conform to a known XML Schema.

屬性會控制 XmlSerializer 類別產生的 XML 資料流,允許您設定 XML 資料流的 XML 命名空間、項目名稱、屬性名稱等等。Attributes control the XML stream generated by the XmlSerializer class, allowing you to set the XML namespace, element name, attribute name, and so on, of the XML stream. 如需這些屬性的詳細資訊以及它們控制 XML 序列化的方式,請參閱使用屬性控制 XML 序列化For more information about these attributes and how they control XML serialization, see Controlling XML Serialization Using Attributes. 如需控制產生的 XML 所用的那些屬性資料表,請參閱控制 XML 序列化的屬性For a table of those attributes that are used to control the generated XML, see Attributes That Control XML Serialization.

XmlSerializer 類別可更進一步序列化物件並且產生編碼的 SOAP XML 資料流。The XmlSerializer class can further serialize an object and generate an encoded SOAP XML stream. 產生的 XML 符合全球資訊網協會之<Simple Object Access Protocol (SOAP) 1.1>文件中的第 5 節。The generated XML adheres to section 5 of the World Wide Web Consortium document titled "Simple Object Access Protocol (SOAP) 1.1." 如需有關此程序的詳細資訊,請參閱How to:物件序列化為 SOAP 編碼的 XML StreamFor more information about this process, see How to: Serialize an Object as a SOAP-Encoded XML Stream. 如需控制產生之 XML 的屬性資料表,請參閱控制編碼 SOAP 序列化的屬性For a table of the attributes that control the generated XML, see Attributes That Control Encoded SOAP Serialization.

XmlSerializer 類別產生 XML Web 服務所建立以及傳遞的 SOAP 訊息。The XmlSerializer class generates the SOAP messages created by, and passed to, XML Web services. 若要控制 SOAP 訊息,可套用屬性至類別、傳回值、參數以及 XML Web 服務檔案 (.asmx) 中的欄位。To control the SOAP messages, you can apply attributes to the classes, return values, parameters, and fields found in an XML Web service file (.asmx). 您可使用列在<控制 XML 序列化的屬性>和<控制編碼 SOAP 序列化的屬性>中的屬性,因為 XML Web 服務可使用常值或編碼的 SOAP 樣式。You can use both the attributes listed in "Attributes That Control XML Serialization" and "Attributes That Control Encoded SOAP Serialization" because an XML Web service can use either the literal or encoded SOAP style. 如需使用屬性控制 XML Web 服務產生之 XML 的詳細資訊,請參閱以 XML Web 服務進行 XML 序列化For more information about using attributes to control the XML generated by an XML Web service, see XML Serialization with XML Web Services. 如需有關 SOAP 與 XML Web 服務的詳細資訊,請參閱自訂 SOAP 訊息格式For more information about SOAP and XML Web services, see Customizing SOAP Message Formatting.

XmlSerializer 應用程式的安全性考量Security Considerations for XmlSerializer Applications

建立使用 XmlSerializer 的應用程式時,您應留意下列項目及其含意:When creating an application that uses the XmlSerializer, you should be aware of the following items and their implications:

  • XmlSerializer 建立 C# (.cs) 檔案並在以 TEMP 環境變數命名的目錄中,將它們編譯成為 .dll 檔案;那些 DLL 會發生序列化。The XmlSerializer creates C# (.cs) files and compiles them into .dll files in the directory named by the TEMP environment variable; serialization occurs with those DLLs.

    注意

    這些序列化組件可預先產生,並且使用 SGen.exe 工具簽署。These serialization assemblies can be generated in advance and signed by using the SGen.exe tool. 這並不是當做 Web 服務的伺服器。This does not work a server of Web services. 換句話說,它只是供用戶端使用以及手動序列化。In other words, it is only for client use and for manual serialization.

    在建立與編譯時,程式碼與 DLL 容易受到惡意處理序的攻擊。The code and the DLLs are vulnerable to a malicious process at the time of creation and compilation. 使用執行 Microsoft Windows NT 4.0 或以上版本的電腦時,有可能讓兩位以上的使用者共用 TEMP 目錄。When using a computer running Microsoft Windows NT 4.0 or later, it might be possible for two or more users to share the TEMP directory. 如果兩個帳戶擁有不同的安全性權限,而且權限較高的帳戶使用 XmlSerializer 執行應用程式,共用 TEMP 目錄會有危險性。Sharing a TEMP directory is dangerous if the two accounts have different security privileges and the higher-privilege account runs an application using the XmlSerializer. 在此例中,一個使用者只要取代編譯的 .cs 或 .dll 檔案,就會破壞電腦的安全性。In this case, one user can breach the computer's security by replacing either the .cs or .dll file that is compiled. 若要去除此顧慮,請確定電腦上各帳戶皆有個別的設定檔。To eliminate this concern, always be sure that each account on the computer has its own profile. 根據預設,TEMP 環境變數是每個帳戶指向不同目錄。By default, the TEMP environment variable points to a different directory for each account.

  • 若惡意使用者對網頁伺服器發送持續 XML 資料流 (阻絕服務攻擊),那麼 XmlSerializer 會持續處理資料直到電腦資源消耗殆盡。If a malicious user sends a continuous stream of XML data to a Web server (a denial of service attack), then the XmlSerializer continues to process the data until the computer runs low on resources.

    若您使用執行 Internet Information Services (IIS) 的電腦,而且您的應用程式是在 IIS 裡執行,就可排除這類攻擊。This kind of attack is eliminated if you are using a computer running Internet Information Services (IIS), and your application is running within IIS. IIS 採用閘道,超過設定量 (預設為 4 KB) 的資料流就不處理。IIS features a gate that does not process streams longer than a set amount (the default is 4 KB). 若您建立不使用 IIS 的應用程式,而且以 XmlSerializer 還原序列化,那應實作類似閘道以防止阻絕服務攻擊。If you create an application that does not use IIS and deserializes with the XmlSerializer, you should implement a similar gate that prevents a denial of service attack.

  • XmlSerializer 序列化資料並且以提供給它的任何類型來執行程式碼。The XmlSerializer serializes data and runs any code using any type given to it.

    惡意物件呈現威脅的方式有兩種。There are two ways in which a malicious object presents a threat. 它可執行惡意程式碼或將惡意程式碼插入 XmlSerializer 所建立的 C# 檔案。It could run malicious code or it could inject malicious code into the C# file created by the XmlSerializer. 在第一個情況下,若惡意物件試圖執行破壞性程序,程式碼存取安全性有助避免造成任何損壞。In the first case, if a malicious object tries to run a destructive procedure, code access security helps prevent any damage from being done. 在第二個情況下,理論上惡意物件有可能以某種方式將程式碼插入到 XmlSerializer 所建立的 C# 檔案。In the second case, there is a theoretical possibility that a malicious object may somehow inject code into the C# file created by the XmlSerializer. 雖然此問題已經徹底檢視,如此的攻擊也被認為非常不可能發生,但您應小心永遠不要以未知和未受信任的型別序列化資料。Although this issue has been examined thoroughly, and such an attack is considered unlikely, you should take the precaution of never serializing data with an unknown and untrusted type.

  • 序列化敏感資料可能會易受攻擊。Serialized sensitive data might be vulnerable.

    在後XmlSerializer擁有序列化資料,可以將它儲存為 XML 檔案或其他資料存放區。After the XmlSerializer has serialized data, it can be stored as an XML file or other data store. 若您的資料存放區可由其他處理序存取,或是在內部網路或網際網路上看得到,那資料就可能遭竊取和惡意使用。If your data store is available to other processes, or is visible on an intranet or the Internet, the data can be stolen and used maliciously. 例如,若您建立了可序列化包含信用卡號碼之訂單的應用程式,這種資料就是高度敏感。For example, if you create an application that serializes orders that include credit card numbers, the data is highly sensitive. 若想要防止它的發生,時時保護資料存放區並採取步驟保持它的私密性。To help prevent this, always protect the store for your data and take steps to keep it private.

簡單類別序列化Serialization of a Simple Class

以下程式碼範例所示為具有公用欄位的基本類別。The following code example shows a basic class with a public field.

Public Class OrderForm
    Public OrderDate As DateTime
End Class
public class OrderForm
{
    public DateTime OrderDate;
}

此類別的執行個體序列化後,可能類似於下列項目。When an instance of this class is serialized, it might resemble the following.

<OrderForm>
    <OrderDate>12/12/01</OrderDate>
</OrderForm>

如需更多序列化範例,請參閱 XML 序列化範例For more examples of serialization, see Examples of XML Serialization.

可序列化的項目Items That Can Be Serialized

下列項目可以使用 XmLSerializer 類別加以序列化:The following items can be serialized using the XmLSerializer class:

  • 共用讀/寫屬性與公用類別的欄位。Public read/write properties and fields of public classes.

  • 可實作 ICollectionIEnumerable 的類別。Classes that implement ICollection or IEnumerable.

    注意

    只序列化集合,公用屬性除外。Only collections are serialized, not public properties.

  • XmlElement 物件。XmlElement objects.

  • XmlNode 物件。XmlNode objects.

  • DataSet 物件。DataSet objects.

如需序列化或還原序列化物件的詳細資訊,請參閱How to:將物件序列化How to:將物件還原序列化For more information about serializing or deserializing objects, see How to: Serialize an Object and How to: Deserialize an Object.

使用 XML 序列化的優點Advantages of Using XML Serialization

XmlSerializer類別可讓您完整而靈活地控制當您序列化物件為 XML。The XmlSerializer class gives you complete and flexible control when you serialize an object as XML. 若您建立 XML Web 服務,可套用控制序列化的屬性至類別與成員,以確保 XML 輸出符合特定結構描述。If you are creating an XML Web service, you can apply attributes that control serialization to classes and members to ensure that the XML output conforms to a specific schema.

例如, XmlSerializer 可讓您:For example, XmlSerializer enables you to:

  • 指定欄位或屬性 (Property) 是否要編碼為屬性 (Attribute) 或項目。Specify whether a field or property should be encoded as an attribute or an element.

  • 指定要使用的 XML 命名空間。Specify an XML namespace to use.

  • 指定若欄位或屬性 (Property) 名稱不當時,項目或屬性 (Attribute) 的名稱。Specify the name of an element or attribute if a field or property name is inappropriate.

XML 序列化的另一項優點是對於您開發的應用程式沒有限制,只要產生的 XML 資料流符合指定的結構描述即可。Another advantage of XML serialization is that you have no constraints on the applications you develop, as long as the XML stream that is generated conforms to a given schema. 試想用來描述書本的結構描述。Imagine a schema that is used to describe books. 它有書名、作者、發行商和 ISBN 編號項目。It features a title, author, publisher, and ISBN number element. 您可開發應用程式,以您想要的任何方式處理 XML 資料,例如書本訂單或書本庫存。You can develop an application that processes the XML data in any way you want, for example, as a book order, or as an inventory of books. 無論是哪一種情況,唯一的要求是 XML 資料流符合指定的 XML 結構描述定義語言 (XSD) 結構描述。In either case, the only requirement is that the XML stream conforms to the specified XML Schema definition language (XSD) schema.

XML 序列化考量XML Serialization Considerations

使用 XmlSerializer 類別時,應考量下列項目:The following should be considered when using the XmlSerializer class:

  • Sgen.exe 工具是特別為了產生序列化組件以達到最佳效能而設計。The Sgen.exe tool is expressly designed to generate serialization assemblies for optimum performance.

  • 序列化資料僅包含資料本身以及您類別的結構。The serialized data contains only the data itself and the structure of your classes. 不包括型別識別與組件資訊。Type identity and assembly information are not included.

  • 只可以序列化公用 (Public) 屬性和欄位。Only public properties and fields can be serialized. 屬性必須有公用存取子 (get 與 set 方法)。Properties must have public accessors (get and set methods). 若您必須對非公用資料序列化,請使用 DataContractSerializer 類別,而非 XML 序列化。If you must serialize non-public data, use the DataContractSerializer class rather than XML serialization.

  • 類別必須有由 XmlSerializer 序列化的預設建構函式。A class must have a default constructor to be serialized by XmlSerializer.

  • 無法將方法序列化。Methods cannot be serialized.

  • XmlSerializer 可以處理的類別是,當 IEnumerableICollection 符合特定需求時,這些類別可以不同的方式實作它們,如下所示。XmlSerializer can process classes that implement IEnumerable or ICollection differently if they meet certain requirements, as follows.

    實作 IEnumerable 的類別必須實作只採用單一參數的公用 Add 方法。A class that implements IEnumerable must implement a public Add method that takes a single parameter. Add 方法的參數必須與 IEnumerator.Current 屬性傳回之類型一致 (多型),此屬性是由 GetEnumerator 方法傳回。The Add method's parameter must be consistent (polymorphic) with the type returned from the IEnumerator.Current property returned from the GetEnumerator method.

    除了 IEnumerable 之外,實作 ICollection 的類別 (例如 CollectionBase) 也必須有採用整數的公用 Item 索引屬性 (C# 的索引子),而且必須具有 integer 類型的公用 Count 屬性。A class that implements ICollection in addition to IEnumerable (such as CollectionBase) must have a public Item indexed property (an indexer in C#) that takes an integer and it must have a public Count property of type integer. 傳遞給 Add 方法的參數必須和 Item 屬性或其中一個類型基底所傳回的類型相同。The parameter passed to the Add method must be the same type as that returned from the Item property, or one of that type's bases.

    針對實作 ICollection 的類別,要序列化的值擷取自索引的 Item 屬性,而不是呼叫 GetEnumerator 進行擷取。For classes that implement ICollection, values to be serialized are retrieved from the indexed Item property rather than by calling GetEnumerator. 同時,不序列化公用欄位與屬性,但傳回其他集合類別 (實作 ICollection) 的公用欄位除外。Also, public fields and properties are not serialized, with the exception of public fields that return another collection class (one that implements ICollection). 如需範例,請參閱 XML 序列化範例For an example, see Examples of XML Serialization.

XSD 資料型別對應XSD Data Type Mapping

W3C 文件XML 結構描述第 2 部分:資料型別XML 結構描述定義語言 (XSD) 結構描述中指定允許的簡單資料類型。The W3C document titled XML Schema Part 2: Datatypes specifies the simple data types that are allowed in an XML Schema definition language (XSD) schema. 許多這些資料類型 (例如,intdecimal),在 .NET Framework 都有對應的資料類型。For many of these (for example, int and decimal), there is a corresponding data type in the .NET Framework. 然而,某些 XML 資料類型在 .NET Framework 中並無對應的資料類型 (例如 NMTOKEN 資料類型)。However, some XML data types do not have a corresponding data type in the .NET Framework (for example, the NMTOKEN data type). 在這種情況下,若您使用 XML 結構描述定義工具 (XML 結構描述定義工具 (Xsd.exe)) 從結構描述產生類別,將套用適當的屬性至類型字串的成員,且它的 DataType 屬性會設為 XML 資料類型名稱。In such cases, if you use the XML Schema Definition tool (XML Schema Definition Tool (Xsd.exe)) to generate classes from a schema, an appropriate attribute is applied to a member of type string, and its DataType property is set to the XML data type name. 例如,若結構描述包括具有 XML 資料類型 NMTOKEN 之名為 "MyToken" 的項目,產生的類別可能包含下列範例所示的成員。For example, if a schema contains an element named "MyToken" with the XML data type NMTOKEN, the generated class might contain a member as shown in the following example.

<XmlElement(DataType:="NMTOKEN")> _
Public MyToken As String
[XmlElement(DataType = "NMTOKEN")]
public string MyToken;

同樣地,若您建立必須符合特定 XML 結構描述 (XSD) 的類別,您應套用適當的屬性並將它的 DataType 屬性設為想要的 XML 資料類型名稱。Similarly, if you are creating a class that must conform to a specific XML Schema (XSD), you should apply the appropriate attribute and set its DataType property to the desired XML data type name.

如需類型對應的完整清單,請參閱下列任一屬性 (attribute) 類別的 DataType 屬性 (property):For a complete list of type mappings, see the DataType property for any of the following attribute classes:

另請參閱See also