XmlElementAttribute 類別

定義

表示在 XmlSerializer 序列化或還原序列化包含 XML 項目的物件時,公用欄位或屬性表示該項目。Indicates that a public field or property represents an XML element when the XmlSerializer serializes or deserializes the object that contains it.

public ref class XmlElementAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.ReturnValue, AllowMultiple=true)]
public class XmlElementAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.ReturnValue, AllowMultiple=true)>]
type XmlElementAttribute = class
    inherit Attribute
Public Class XmlElementAttribute
Inherits Attribute
繼承
XmlElementAttribute
屬性

範例

下列範例會序列化名為的類別 Group ,並將其套用 XmlElementAttribute 至數個成員。The following example serializes a class named Group and applies the XmlElementAttribute to several of its members. 名為的欄位會傳回 Employees 物件的陣列 EmployeeThe field named Employees returns an array of Employee objects. 在此情況下, XmlElementAttribute 會指定產生的 XML 將不會被嵌套 (這是陣列) 中專案的預設行為。In this case, the XmlElementAttribute specifies that the resulting XML will not be nested (which is the default behavior of items in an array).

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

using namespace System;
using namespace System::Collections;
using namespace System::IO;
using namespace System::Xml::Serialization;
public ref class Employee
{
public:
   String^ Name;
};

public ref class Manager: public Employee
{
public:
   int Level;
};

public ref class Group
{
public:

   /* Set the element name and namespace of the XML element.
      By applying an XmlElementAttribute to an array,  you instruct
      the XmlSerializer to serialize the array as a series of XML
      elements, instead of a nested set of elements. */

   [XmlElement(
   ElementName="Members",
   Namespace="http://www.cpandl.com")]
   array<Employee^>^Employees;

   [XmlElement(DataType="snippet1>",
   ElementName="Building")]
   double GroupID;

   [XmlElement(DataType="hexBinary")]
   array<Byte>^HexBytes;

   [XmlElement(DataType="boolean")]
   bool IsActive;

   [XmlElement(Type=::Manager::typeid)]
   Employee^ Manager;

   [XmlElement(Int32::typeid,
   ElementName="ObjectNumber"),
   XmlElement(String::typeid,
   ElementName="ObjectString")]
   ArrayList^ ExtraInfo;
};

void SerializeObject( String^ filename )
{
   // Create the XmlSerializer.
   XmlSerializer^ s = gcnew XmlSerializer( Group::typeid );

   // To write the file, a TextWriter is required.
   TextWriter^ writer = gcnew StreamWriter( filename );

   /* Create an instance of the group to serialize, and set
      its properties. */
   Group^ group = gcnew Group;
   group->GroupID = 10.089f;
   group->IsActive = false;
   array<Byte>^temp0 = {Convert::ToByte( 100 )};
   group->HexBytes = temp0;
   Employee^ x = gcnew Employee;
   Employee^ y = gcnew Employee;
   x->Name = "Jack";
   y->Name = "Jill";
   array<Employee^>^temp1 = {x,y};
   group->Employees = temp1;
   Manager^ mgr = gcnew Manager;
   mgr->Name = "Sara";
   mgr->Level = 4;
   group->Manager = mgr;

   /* Add a number and a string to the 
      ArrayList returned by the ExtraInfo property. */
   group->ExtraInfo = gcnew ArrayList;
   group->ExtraInfo->Add( 42 );
   group->ExtraInfo->Add( "Answer" );

   // Serialize the object, and close the TextWriter.      
   s->Serialize( writer, group );
   writer->Close();
}

void DeserializeObject( String^ filename )
{
   FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
   XmlSerializer^ x = gcnew XmlSerializer( Group::typeid );
   Group^ g = dynamic_cast<Group^>(x->Deserialize( fs ));
   Console::WriteLine( g->Manager->Name );
   Console::WriteLine( g->GroupID );
   Console::WriteLine( g->HexBytes[ 0 ] );
   IEnumerator^ myEnum = g->Employees->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Employee^ e = safe_cast<Employee^>(myEnum->Current);
      Console::WriteLine( e->Name );
   }
}

int main()
{
   SerializeObject( "FirstDoc.xml" );
   DeserializeObject( "FirstDoc.xml" );
}
using System;
using System.Collections;
using System.IO;
using System.Xml.Serialization;

public class Group
{
   /* Set the element name and namespace of the XML element.
   By applying an XmlElementAttribute to an array,  you instruct
   the XmlSerializer to serialize the array as a series of XML
   elements, instead of a nested set of elements. */

   [XmlElement(
   ElementName = "Members",
   Namespace = "http://www.cpandl.com")]
   public Employee[] Employees;

   [XmlElement(DataType = "double",
   ElementName = "Building")]
   public double GroupID;

   [XmlElement(DataType = "hexBinary")]
   public byte [] HexBytes;

   [XmlElement(DataType = "boolean")]
   public bool IsActive;

   [XmlElement(Type = typeof(Manager))]
   public Employee Manager;

   [XmlElement(typeof(int),
   ElementName = "ObjectNumber"),
   XmlElement(typeof(string),
   ElementName = "ObjectString")]
   public ArrayList ExtraInfo;
}

public class Employee
{
   public string Name;
}

public class Manager:Employee{
   public int Level;
}

public class Run
{
    public static void Main()
    {
       Run test = new Run();
       test.SerializeObject("FirstDoc.xml");
       test.DeserializeObject("FirstDoc.xml");
    }

   public void SerializeObject(string filename)
   {
      // Create the XmlSerializer.
      XmlSerializer s = new XmlSerializer(typeof(Group));

      // To write the file, a TextWriter is required.
      TextWriter writer = new StreamWriter(filename);

      /* Create an instance of the group to serialize, and set
         its properties. */
      Group group = new Group();
      group.GroupID = 10.089f;
      group.IsActive = false;

      group.HexBytes = new byte[1]{Convert.ToByte(100)};

      Employee x = new Employee();
      Employee y = new Employee();

      x.Name = "Jack";
      y.Name = "Jill";

      group.Employees = new Employee[2]{x,y};

      Manager mgr = new Manager();
      mgr.Name = "Sara";
      mgr.Level = 4;
      group.Manager = mgr;

      /* Add a number and a string to the
      ArrayList returned by the ExtraInfo property. */
      group.ExtraInfo = new ArrayList();
      group.ExtraInfo.Add(42);
      group.ExtraInfo.Add("Answer");

      // Serialize the object, and close the TextWriter.
      s.Serialize(writer, group);
      writer.Close();
   }

   public void DeserializeObject(string filename)
   {
      FileStream fs = new FileStream(filename, FileMode.Open);
      XmlSerializer x = new XmlSerializer(typeof(Group));
      Group g = (Group) x.Deserialize(fs);
      Console.WriteLine(g.Manager.Name);
      Console.WriteLine(g.GroupID);
      Console.WriteLine(g.HexBytes[0]);
      foreach(Employee e in g.Employees)
      {
         Console.WriteLine(e.Name);
      }
   }
}

Imports System.Collections
Imports System.IO
Imports System.Xml.Serialization


Public Class Group
    ' Set the element name and namespace of the XML element.
    <XmlElement(ElementName := "Members", _
     Namespace := "http://www.cpandl.com")> _    
    Public Employees() As Employee
    
    <XmlElement(DataType := "double", _
     ElementName := "Building")> _
    Public GroupID As Double
    
    <XmlElement(DataType := "hexBinary")> _
    Public HexBytes() As Byte
    
    <XmlElement(DataType := "boolean")> _
    Public IsActive As Boolean
    
    <XmlElement(GetType(Manager))> _
    Public Manager As Employee
    
    <XmlElement(GetType(Integer), _
        ElementName := "ObjectNumber"), _
     XmlElement(GetType(String), _
        ElementName := "ObjectString")> _
    Public ExtraInfo As ArrayList
End Class

Public Class Employee
    Public Name As String
End Class

Public Class Manager
    Inherits Employee
    Public Level As Integer
End Class

Public Class Run
    
    Public Shared Sub Main()
        Dim test As New Run()
        test.SerializeObject("FirstDoc.xml")
        test.DeserializeObject("FirstDoc.xml")
    End Sub
    
    Public Sub SerializeObject(filename As String)
        ' Create the XmlSerializer.
        Dim s As New XmlSerializer(GetType(Group))
        
        ' To write the file, a TextWriter is required.
        Dim writer As New StreamWriter(filename)
        
        ' Create an instance of the group to serialize, and set
        ' its properties. 
        Dim group As New Group()
        group.GroupID = 10.089f
        group.IsActive = False
        
        group.HexBytes = New Byte() {Convert.ToByte(100)}
        
        Dim x As New Employee()
        Dim y As New Employee()
        
        x.Name = "Jack"
        y.Name = "Jill"
        
        group.Employees = New Employee() {x, y}
        
        Dim mgr As New Manager()
        mgr.Name = "Sara"
        mgr.Level = 4
        group.Manager = mgr
        
        ' Add a number and a string to the
        ' ArrayList returned by the ExtraInfo property. 
        group.ExtraInfo = New ArrayList()
        group.ExtraInfo.Add(42)
        group.ExtraInfo.Add("Answer")
        
        ' Serialize the object, and close the TextWriter.      
        s.Serialize(writer, group)
        writer.Close()
    End Sub    
    
    Public Sub DeserializeObject(filename As String)
        Dim fs As New FileStream(filename, FileMode.Open)
        Dim x As New XmlSerializer(GetType(Group))
        Dim g As Group = CType(x.Deserialize(fs), Group)
        Console.WriteLine(g.Manager.Name)
        Console.WriteLine(g.GroupID)
        Console.WriteLine(g.HexBytes(0))

        Dim e As Employee
        For Each e In g.Employees
            Console.WriteLine(e.Name)
        Next e
    End Sub
End Class

備註

XmlElementAttribute屬於一系列屬性,可控制序列化或還原序列化 XmlSerializer 物件的方式。The XmlElementAttribute belongs to a family of attributes that controls how the XmlSerializer serializes or deserializes an object. 如需類似屬性的完整清單,請參閱 控制 XML 序列化的屬性For a complete list of similar attributes, see Attributes That Control XML Serialization.

XML 檔通常包含 XML 元素,其中每個專案都包含三個部分:具有可能屬性的開頭標記、結束記號,以及標記之間的資料。An XML document usually contains XML elements, each of which consists of three parts: an opening tag with possible attributes, a closing tag, and the data between the tags. XML 標記可以是嵌套的,也就是標記之間的資料也可以是 XML 元素。XML tags can be nested--that is, the data between tags can also be XML elements. 其中一個專案的這個容量可以用來括住另一個專案,讓檔包含資料的階層。This capacity of one element to enclose another allows the document to contain hierarchies of data. XML 元素也可以包含屬性。An XML element can also include attributes.

將套用 XmlElementAttribute 至公用欄位或公用讀取/寫入屬性,以控制 XML 元素的特性,例如專案名稱和命名空間。Apply the XmlElementAttribute to public fields or public read/write properties to control characteristics of the XML elements such as the element name and namespace.

XmlElementAttribute可以多次套用至傳回物件陣列的欄位。The XmlElementAttribute can be applied multiple times to a field that returns an array of objects. 其目的是要透過屬性指定 (, Type) 可插入陣列中的不同類型。The purpose of this is to specify (through the Type property) different types that can be inserted into the array. 例如,下列 c # 程式碼中的陣列會接受字串和整數。For example, the array in the following C# code accepts both strings and integers.

public class Things{  
   [XmlElement(Type = typeof(string)),  
   XmlElement(Type = typeof(int))]  
   public object[] StringsAndInts;  
}  

這會產生如下所示的 XML。This results in XML that might resemble the following.

<Things>  
   <string>Hello</string>  
   <int>999</int>  
   <string>World</string>  
</Things>  

請注意,當您套用 XmlElementAttribute 多次但未指定 ElementName 屬性值時,專案會以可接受物件的類型命名。Note that when you apply the XmlElementAttribute multiple times without specifying an ElementName property value, the elements are named after the type of the acceptable objects.

如果您將套用 XmlElementAttribute 至傳回陣列的欄位或屬性,則會將陣列中的專案編碼為 XML 元素序列。If you apply the XmlElementAttribute to a field or property that returns an array, the items in the array are encoded as a sequence of XML elements.

相反地,如果未套用 XmlElementAttribute 至這類欄位或屬性,則會將陣列中的專案編碼為一連串的專案,並在以欄位或屬性命名的元素底下進行嵌套。In contrast if an XmlElementAttribute is not applied to such a field or property, the items in the array are encoded as a sequence of elements, nested under an element named after the field or property. (使用 XmlArrayAttributeXmlArrayItemAttribute 屬性來控制陣列的序列化方式。 ) (Use the XmlArrayAttribute and XmlArrayItemAttribute attributes to control how an array is serialized.)

您可以設定 Type 屬性來指定衍生自原始欄位或屬性之類型的類型,也就是您已套用的欄位或屬性 XmlElementAttributeYou can set the Type property to specify a type that is derived from the type of the original field or property--that is, the field or property to which you have applied the XmlElementAttribute.

如果欄位或屬性傳回 ArrayList ,則您可以將的多個實例套用 XmlElementAttribute 至成員。If a field or property returns an ArrayList, you can apply multiple instances of the XmlElementAttribute to the member. 對於每個實例,請將 Type 屬性設定為可插入陣列中的物件類型。For each instance, set the Type property to a type of object that can be inserted into the array.

如需使用屬性的詳細資訊,請參閱 屬性For more information about using attributes, see Attributes.

注意

您可以 XmlElement 在程式碼中使用這個字,而不是使用較長的時間 XmlElementAttributeYou can use the word XmlElement in your code instead of the longer XmlElementAttribute.

建構函式

XmlElementAttribute()

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

XmlElementAttribute(String)

初始化 XmlElementAttribute 類別的新執行個體,並且指定 XML 項目的名稱。Initializes a new instance of the XmlElementAttribute class and specifies the name of the XML element.

XmlElementAttribute(String, Type)

初始化 XmlElementAttribute 的新執行個體,並針對套用 XmlElementAttribute 的成員指定 XML 項目名稱和衍生型別。Initializes a new instance of the XmlElementAttribute and specifies the name of the XML element and a derived type for the member to which the XmlElementAttribute is applied. 這個成員型別用於 XmlSerializer 序列化包含它的物件時。This member type is used when the XmlSerializer serializes the object that contains it.

XmlElementAttribute(Type)

初始化 XmlElementAttribute 類別的新執行個體,並針對套用 XmlElementAttribute 的成員指定型別。Initializes a new instance of the XmlElementAttribute class and specifies a type for the member to which the XmlElementAttribute is applied. 序列化或還原序列化包含這個型別的物件時,XmlSerializer 會使用該型別。This type is used by the XmlSerializer when serializing or deserializing object that contains it.

屬性

DataType

取得或設定 XmlSerializer 所產生 XML 項目的 XML 結構描述定義 (XSD) 資料型別。Gets or sets the XML Schema definition (XSD) data type of the XML element generated by the XmlSerializer.

ElementName

取得或設定產生的 XML 項目的名稱。Gets or sets the name of the generated XML element.

Form

取得或設定值,指出項目是否為限定的。Gets or sets a value that indicates whether the element is qualified.

IsNullable

取得或設定值,指出 XmlSerializer 是否必須將設為 null 的成員序列化為 xsi:nil 屬性設為 true 的空標記。Gets or sets a value that indicates whether the XmlSerializer must serialize a member that is set to null as an empty tag with the xsi:nil attribute set to true.

Namespace

取得或設定指派給類別序列化時所產生之 XML 項目的命名空間。Gets or sets the namespace assigned to the XML element that results when the class is serialized.

Order

取得或設定項目序列化或還原序列化的明確順序。Gets or sets the explicit order in which the elements are serialized or deserialized.

Type

取得或設定用來表示 XML 項目的物件類型。Gets or sets the object type used to represent the XML element.

TypeId

在衍生類別中實作時,取得這個 Attribute 的唯一識別碼。When implemented in a derived class, gets a unique identifier for this Attribute.

(繼承來源 Attribute)

方法

Equals(Object)

傳回值,這個值指出此執行個體是否與指定的物件相等。Returns a value that indicates whether this instance is equal to a specified object.

(繼承來源 Attribute)
GetHashCode()

傳回這個執行個體的雜湊碼。Returns the hash code for this instance.

(繼承來源 Attribute)
GetType()

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

(繼承來源 Object)
IsDefaultAttribute()

在衍生類別中覆寫時,表示這個執行個體的值是衍生類別的預設值。When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.

(繼承來源 Attribute)
Match(Object)

在衍生類別中覆寫時,會傳回值,表示這個執行個體是否等於指定物件。When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(繼承來源 Attribute)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
ToString()

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

(繼承來源 Object)

明確介面實作

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

將一組名稱對應至一組對應的分派識別項 (Dispatch Identifier)。Maps a set of names to a corresponding set of dispatch identifiers.

(繼承來源 Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

擷取物件的類型資訊,可以用來取得介面的類型資訊。Retrieves the type information for an object, which can be used to get the type information for an interface.

(繼承來源 Attribute)
_Attribute.GetTypeInfoCount(UInt32)

擷取物件提供的類型資訊介面數目 (0 或 1)。Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(繼承來源 Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

提供物件所公開的屬性和方法的存取權。Provides access to properties and methods exposed by an object.

(繼承來源 Attribute)

適用於

另請參閱