XmlElementAttribute XmlElementAttribute XmlElementAttribute XmlElementAttribute Class

定義

表示在 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)]
[System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.ReturnValue, AllowMultiple=true)]
public class XmlElementAttribute : Attribute
type XmlElementAttribute = class
    inherit Attribute
Public Class XmlElementAttribute
Inherits Attribute
繼承
XmlElementAttributeXmlElementAttributeXmlElementAttributeXmlElementAttribute
屬性

範例

下列範例會序列化類別,名為Group,並套用XmlElementAttribute至其成員數。The following example serializes a class named Group and applies the XmlElementAttribute to several of its members. 名為的欄位Employees傳回的陣列Employee物件。The 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
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.

注意

您可以使用 wordXmlElement代替較長的程式碼中XmlElementAttributeYou can use the word XmlElement in your code instead of the longer XmlElementAttribute.

建構函式

XmlElementAttribute() XmlElementAttribute() XmlElementAttribute() XmlElementAttribute()

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

XmlElementAttribute(String) XmlElementAttribute(String) XmlElementAttribute(String) XmlElementAttribute(String)

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

XmlElementAttribute(String, Type) XmlElementAttribute(String, Type) XmlElementAttribute(String, Type) 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(Type) XmlElementAttribute(Type) 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 DataType DataType DataType

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

ElementName ElementName ElementName ElementName

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

Form Form Form Form

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

IsNullable IsNullable IsNullable 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 Namespace Namespace Namespace

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

Order Order Order Order

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

Type Type Type Type

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

TypeId TypeId TypeId TypeId

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

(Inherited from Attribute)

方法

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

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

(Inherited from Attribute)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

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

(Inherited from Attribute)
GetType() GetType() GetType() GetType()

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

(Inherited from Object)
IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute()

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

(Inherited from Attribute)
Match(Object) Match(Object) Match(Object) Match(Object)

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

(Inherited from Attribute)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

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

(Inherited from Object)
ToString() ToString() ToString() ToString()

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

(Inherited from Object)

明確介面實作

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

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

(Inherited from Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

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

(Inherited from Attribute)
_Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32)

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

(Inherited from Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

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

(Inherited from Attribute)

適用於

另請參閱