使用屬性控制 XML 序列化Controlling XML Serialization Using Attributes

屬性可用來控制物件的 XML 序列化或從相同的類別集建立其他的 XML 資料流。Attributes can be used to control the XML serialization of an object or to create an alternate XML stream from the same set of classes. 如需有關建立替代 XML 資料流的詳細資訊,請參閱How to:指定 XML Stream 的替代項目名稱For more details about creating an alternate XML stream, see How to: Specify an Alternate Element Name for an XML Stream.

注意

如果產生的 XML 必須符合第 5 節的 World Wide Web Consortium (W3C) 文件簡易物件存取通訊協定 (SOAP) 1.1,使用屬性中所列屬性,控制編碼 SOAP序列化If the XML generated must conform to section 5 of the World Wide Web Consortium (W3C) document titled Simple Object Access Protocol (SOAP) 1.1, use the attributes listed in Attributes That Control Encoded SOAP Serialization.

根據預設,XML 項目名稱是由類別或成員名稱決定。By default, an XML element name is determined by the class or member name. 在名為 Book 的簡單類別中,名為 ISBN 的欄位將會產生 XML 項目標記 <ISBN>,如下列範例所示。In a simple class named Book, a field named ISBN will produce an XML element tag <ISBN>, as shown in the following example.

Public Class Book
    Public ISBN As String
End Class
' When an instance of the Book class is serialized, it might
' produce this XML:
' <ISBN>1234567890</ISBN>.
public class Book
{
    public string ISBN;
}
// When an instance of the Book class is serialized, it might
// produce this XML:
// <ISBN>1234567890</ISBN>.

若想指定項目一個新的名稱,可以變更此預設行為。This default behavior can be changed if you want to give the element a new name. 下列程式碼顯示一個屬性 (Attribute) 如何透過設定 ElementNameXmlElementAttribute的 屬性 (Property),達成這個目標。The following code shows how an attribute enables this by setting the ElementName property of a XmlElementAttribute.

Public Class TaxRates
   < XmlElement(ElementName = "TaxRate")> _
    Public ReturnTaxRate As Decimal
End Class
public class TaxRates {
    [XmlElement(ElementName = "TaxRate")]
    public decimal ReturnTaxRate;
}

如需屬性的詳細資訊,請參閱屬性For more information about attributes, see Attributes. 如需控制 XML 序列化的屬性清單,請參閱可控制 XML 序列化的屬性For a list of attributes that control XML serialization, see Attributes That Control XML Serialization.

控制陣列序列化Controlling Array Serialization

XmlArrayAttributeXmlArrayItemAttribute 屬性是針對陣列序列化控制而設計。The XmlArrayAttribute and the XmlArrayItemAttribute attributes are designed to control the serialization of arrays. 使用這些屬性,您可以控制的項目名稱、 命名空間和 XML 結構描述 (XSD) 資料類型 (如全球資訊網協會 [www.w3.org] 文件中定義 「 XML 結構描述第 2 部分:資料型別 」)。Using these attributes, you can control the element name, namespace, and XML Schema (XSD) data type (as defined in the World Wide Web Consortium [www.w3.org] document titled "XML Schema Part 2: Datatypes"). 您也可以指定陣列能包含的類型。You can also specify the types that can be included in an array.

XmlArrayAttribute 將決定當陣列序列化時,封入 XML 項目的屬性。The XmlArrayAttribute will determine the properties of the enclosing XML element that results when an array is serialized. 例如,依預設,序列化以下的陣列將產生名為 Employees 的 XML 項目。For example, by default, serializing the array below will result in an XML element named Employees. Employees 項目將包含一系列根據陣列類型 Employee命名的項目。The Employees element will contain a series of elements named after the array type Employee.

Public Class Group
    Public Employees() As Employee
End Class
Public Class Employee
    Public Name As String
End Class
public class Group {
    public Employee[] Employees;
}
public class Employee {
    public string Name;
}

序列化的執行個體可能類似於下列項目。A serialized instance might resemble the following.

<Group>
<Employees>
    <Employee>
        <Name>Haley</Name>
    </Employee>
</Employees>
</Group>

套用 XmlArrayAttribute,您可變更 XML 項目的名稱,如下所示。By applying a XmlArrayAttribute, you can change the name of the XML element, as follows.

Public Class Group
    <XmlArray("TeamMembers")> _
    Public Employees() As Employee
End Class
public class Group {
    [XmlArray("TeamMembers")]
    public Employee[] Employees;
}

產生的 XML 可能類似下列所示。The resulting XML might resemble the following.

<Group>
<TeamMembers>
    <Employee>
        <Name>Haley</Name>
    </Employee>
</TeamMembers>
</Group>

另一方面,XmlArrayItemAttribute 控制陣列包含的項目如何序列化。The XmlArrayItemAttribute, on the other hand, controls how the items contained in the array are serialized. 請注意,屬性會套用至傳回陣列的欄位。Note that the attribute is applied to the field returning the array.

Public Class Group
    <XmlArrayItem("MemberName")> _
    Public Employee() As Employees
End Class
public class Group {
    [XmlArrayItem("MemberName")]
    public Employee[] Employees;
}

產生的 XML 可能類似下列所示。The resulting XML might resemble the following.

<Group>
<Employees>
    <MemberName>Haley</MemberName>
</Employees>
</Group>

序列化衍生類別Serializing Derived Classes

XmlArrayItemAttribute 的另一用途,是允許衍生類別的序列化。Another use of the XmlArrayItemAttribute is to allow the serialization of derived classes. 例如,另一個衍生自 Manager 名為 Employee 的類別,可加入前面的範例。For example, another class named Manager that derives from Employee can be added to the previous example. 若您不套用 XmlArrayItemAttribute,由於無法識別衍生類別型別,程式碼將在執行階段失敗。If you do not apply the XmlArrayItemAttribute, the code will fail at run time because the derived class type will not be recognized. 若要修正此狀況,請套用屬性兩次,每次都針對每個可接受的型別 (基底與衍生) 設定 Type 屬性。To remedy this, apply the attribute twice, each time setting the Type property for each acceptable type (base and derived).

Public Class Group
    <XmlArrayItem(Type:=GetType(Employee)), _
    XmlArrayItem(Type:=GetType(Manager))> _
    Public Employees() As Employee
End Class
Public Class Employee
    Public Name As String
End Class
Public Class Manager
Inherits Employee
    Public Level As Integer
End Class
public class Group {
    [XmlArrayItem(Type = typeof(Employee)),
    XmlArrayItem(Type = typeof(Manager))]
    public Employee[] Employees;
}
public class Employee {
    public string Name;
}
public class Manager:Employee {
    public int Level;
}

序列化的執行個體可能類似於下列項目。A serialized instance might resemble the following.

<Group>
<Employees>
    <Employee>
        <Name>Haley</Name>
    </Employee>
    <Employee xsi:type = "Manager">
        <Name>Ann</Name>
        <Level>3</Level>
    <Employee>
</Employees>
</Group>

序列化陣列成為項目序列Serializing an Array as a Sequence of Elements

您也可以套用 XmlElementAttribute 至傳回陣列的欄位 (如下所示),將陣列序列化成為 XML 項目的平面序列。You can also serialize an array as a flat sequence of XML elements by applying a XmlElementAttribute to the field returning the array as follows.

Public Class Group
    <XmlElement> _
    Public Employees() As Employee
End Class
public class Group {
    [XmlElement]
    public Employee[] Employees;
}

序列化的執行個體可能類似於下列項目。A serialized instance might resemble the following.

<Group>
<Employees>
    <Name>Haley</Name>
</Employees>
<Employees>
    <Name>Noriko</Name>
</Employees>
<Employees>
    <Name>Marco</Name>
</Employees>
</Group>

另一種區別這兩種 XML 資料流的方法是使用 XML 結構描述定義工具,從編譯的程式碼中產生 XML 結構描述 (XSD) 文件檔案 Another way to differentiate the two XML streams is to use the XML Schema Definition tool to generate the XML Schema (XSD) document files from the compiled code. (如需使用此工具的詳細資料,請參閱 XML 結構描述定義工具和 XML 序列化)。無屬性套用至欄位時,結構描述會以下列方式說明項目。(For more details on using the tool, see The XML Schema Definition Tool and XML Serialization.) When no attribute is applied to the field, the schema describes the element in the following manner.

<xs:element minOccurs="0" maxOccurs ="1" name="Employees" type="ArrayOfEmployee" />

XmlElementAttribute 套用至欄位時,產生的結構描述說明項目如下。When the XmlElementAttribute is applied to the field, the resulting schema describes the element as follows.

<xs:element minOccurs="0" maxOccurs="unbounded" name="Employees" type="Employee" /> 

序列化 ArrayListSerializing an ArrayList

ArrayList 類別可包含各種不同物件的集合。The ArrayList class can contain a collection of diverse objects. 因此您可如同使用陣列的方式使用 ArrayListYou can therefore use a ArrayList much as you use an array. 不過,若不想建立會傳回型別物件陣列的欄位,可建立傳回單一 ArrayList的欄位。Instead of creating a field that returns an array of typed objects, however, you can create a field that returns a single ArrayList. 不過,與陣列一樣,您必須將 XmlSerializer 包含的物件類型告知 ArrayListHowever, as with arrays, you must inform the XmlSerializer of the types of objects the ArrayList contains. 若要達成這個目的,請指派多個 XmlElementAttribute 執行個體至欄位,如下面的範例所示。To accomplish this, assign multiple instances of the XmlElementAttribute to the field, as shown in the following example.

Public Class Group
    <XmlElement(Type:=GetType(Employee)), _
    XmlElement(Type:=GetType(Manager))> _
    Public Info As ArrayList
End Class
public class Group {
    [XmlElement(Type = typeof(Employee)), 
    XmlElement(Type = typeof(Manager))]
    public ArrayList Info;
}

使用 XmlRootAttribute 與 XmlTypeAttribute 控制類別的序列化Controlling Serialization of Classes Using XmlRootAttribute and XmlTypeAttribute

有兩種屬性可套用至類別 (只有一種類別):XmlRootAttributeXmlTypeAttributeThere are two attributes that can be applied to a class (and only a class): XmlRootAttribute and XmlTypeAttribute. 這些屬性非常類似。These attributes are very similar. XmlRootAttribute 僅能套用至一類別:在序列化後此類別代表 XML 文件開啟與關閉的項目,換句話說就是根項目。The XmlRootAttribute can be applied to only one class: the class that, when serialized, represents the XML document's opening and closing element—in other words, the root element. 另一方面,XmlTypeAttribute 可套用至任何類別,包括根類別。The XmlTypeAttribute, on the other hand, can be applied to any class, including the root class.

例如,在前述的範例中,Group 類別為根類別,它所有的公用欄位與屬性成為在 XML 文件中發現的 XML 項目。For example, in the previous examples, the Group class is the root class, and all its public fields and properties become the XML elements found in the XML document. 因此,只能有一個根類別。Therefore, there can be only one root class. 藉由套用 XmlRootAttribute,您可用 XmlSerializer控制產生的 XML 資料流。By applying the XmlRootAttribute, you can control the XML stream generated by the XmlSerializer. 例如,您可變更項目名稱與命名空間。For example, you can change the element name and namespace.

XmlTypeAttribute 允許您控制產生之 XML 的結構描述。The XmlTypeAttribute allows you to control the schema of the generated XML. 當您需要透過 XML Web 服務發怖此結構描述時,此能力就很重要。This capability is useful when you need to publish the schema through an XML Web service. 下列範例會將 XmlTypeAttributeXmlRootAttribute套用至相同類別。The following example applies both the XmlTypeAttribute and the XmlRootAttribute to the same class.

<XmlRoot("NewGroupName"), _
XmlType("NewTypeName")> _
Public Class Group
    Public Employees() As Employee
End Class
[XmlRoot("NewGroupName")]
[XmlType("NewTypeName")]
public class Group {
    public Employee[] Employees;
}

如果此類別已編譯,且使用 XML 結構描述定義工具產生它的結構描述,您會發現下列的 XML 說明 GroupIf this class is compiled, and the XML Schema Definition tool is used to generate its schema, you would find the following XML describing Group.

<xs:element name="NewGroupName" type="NewTypeName">

相反地,若您要序列化類別的執行個體,在 XML 文件中只會發現 NewGroupNameIn contrast, if you were to serialize an instance of the class, only NewGroupName would be found in the XML document.

<NewGroupName>
    . . .
</NewGroupName>

避免以 XmlIgnoreAttribute 序列化Preventing Serialization with the XmlIgnoreAttribute

也有可能不需將公用屬性或欄位序列化的狀況。There might be situations when a public property or field does not need to be serialized. 例如,欄位或屬性可用來包含中繼資料。For example, a field or property could be used to contain metadata. 在這樣的情況下,套用 XmlIgnoreAttribute 至欄位或屬性,且將略過 XmlSerializerIn such cases, apply the XmlIgnoreAttribute to the field or property and the XmlSerializer will skip over it.

另請參閱See also