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
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 的字段返回 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.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. (使用 "XmlArrayAttribute" 和 "XmlArrayItemAttribute" 属性控制序列化数组的方式。)(Use the XmlArrayAttribute and XmlArrayItemAttribute attributes to control how an array is serialized.)

可以设置 Type 属性来指定派生自原始字段或属性的类型的类型(即,已将 XmlElementAttribute应用到的字段或属性)。You 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.

备注

您可以在代码中使用 word 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 的新实例,并指定 XML 元素的名称和 XmlElementAttribute 应用到的成员的派生类型。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 元素的命名空间,这些 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)

将一组名称映射为对应的一组调度标识符。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)

适用于

另请参阅