XmlElementAttribute XmlElementAttribute XmlElementAttribute XmlElementAttribute Class

Definición

Indica que un campo público o una propiedad pública representa un elemento XML, cuando XmlSerializer serializa o deserializa el objeto que lo contiene.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
Herencia
XmlElementAttributeXmlElementAttributeXmlElementAttributeXmlElementAttribute
Atributos

Ejemplos

El siguiente ejemplo serializa una clase denominada Group y se aplica el XmlElementAttribute a varios de sus miembros.The following example serializes a class named Group and applies the XmlElementAttribute to several of its members. El campo denominado Employees devuelve una matriz de Employee objetos.The field named Employees returns an array of Employee objects. En este caso, el XmlElementAttribute especifica que el XML resultante no se anidarán (que es el comportamiento predeterminado de los elementos de matriz).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

Comentarios

El XmlElementAttribute pertenece a una familia de atributos que controla cómo el XmlSerializer serializa o deserializa un objeto.The XmlElementAttribute belongs to a family of attributes that controls how the XmlSerializer serializes or deserializes an object. Para obtener una lista completa de atributos similares, vea Attributes That Control XML Serialization.For a complete list of similar attributes, see Attributes That Control XML Serialization.

Normalmente, un documento XML contiene elementos XML, cada uno de los cuales consta de tres partes: una etiqueta de apertura con atributos posibles, una etiqueta de cierre y los datos entre las etiquetas.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. Etiquetas XML se pueden anidar, que es, los datos entre las etiquetas también pueden ser elementos XML.XML tags can be nested--that is, the data between tags can also be XML elements. Esta capacidad de un elemento para incluir otro permite que el documento que contiene las jerarquías de datos.This capacity of one element to enclose another allows the document to contain hierarchies of data. Un elemento XML también puede incluir atributos.An XML element can also include attributes.

Aplicar el XmlElementAttribute a campos públicos o propiedades públicas de lectura/escritura para controlar las características de los elementos XML como el nombre de elemento y espacio de nombres.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.

El XmlElementAttribute se puede aplicar varias veces a un campo que devuelve una matriz de objetos.The XmlElementAttribute can be applied multiple times to a field that returns an array of objects. El propósito de esto es especificar (a través de la Type propiedad) distintos tipos que se pueden insertar en la matriz.The purpose of this is to specify (through the Type property) different types that can be inserted into the array. Por ejemplo, la matriz en el siguiente código de C# acepta cadenas y enteros.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;  
}  

Esto da como resultado en XML que puede ser similar a lo siguiente.This results in XML that might resemble the following.

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

Tenga en cuenta que al aplicar el XmlElementAttribute varias veces sin especificar un ElementName valor de propiedad, los elementos se denominan después del tipo de los objetos aceptables.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.

Si aplica el XmlElementAttribute a un campo o propiedad que devuelve una matriz, los elementos de la matriz se codifican como una secuencia de elementos 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.

En cambio si un XmlElementAttribute no se aplica a este campo o propiedad, los elementos de la matriz se codifican como una secuencia de elementos, anidados bajo un elemento con el nombre de campo o propiedad.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. (Use el XmlArrayAttribute y XmlArrayItemAttribute atributos para controlar cómo se serializa una matriz.)(Use the XmlArrayAttribute and XmlArrayItemAttribute attributes to control how an array is serialized.)

Puede establecer el Type propiedad para especificar un tipo que se deriva el tipo de campo o propiedad--original es decir, campo o propiedad a la que ha aplicado el 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.

Si un campo o propiedad devuelve un ArrayList, puede aplicar varias instancias de la XmlElementAttribute al miembro.If a field or property returns an ArrayList, you can apply multiple instances of the XmlElementAttribute to the member. Para cada instancia, establezca el Type propiedad a un tipo de objeto que se puede insertar en la matriz.For each instance, set the Type property to a type of object that can be inserted into the array.

Para obtener más información sobre el uso de atributos, vea atributos.For more information about using attributes, see Attributes.

Nota

Puede usar la palabra XmlElement en el código en lugar de la forma más larga XmlElementAttribute.You can use the word XmlElement in your code instead of the longer XmlElementAttribute.

Constructores

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

Inicializa una nueva instancia de la clase XmlElementAttribute.Initializes a new instance of the XmlElementAttribute class.

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

Inicializa una nueva instancia de la clase XmlElementAttribute y especifica el nombre del elemento 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)

Inicializa una nueva instancia de XmlElementAttribute y especifica el nombre del elemento XML así como un tipo derivado del miembro al que se ha aplicado 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. Este tipo de miembro se utiliza cuando XmlSerializer serializa el objeto que lo contiene.This member type is used when the XmlSerializer serializes the object that contains it.

XmlElementAttribute(Type) XmlElementAttribute(Type) XmlElementAttribute(Type) XmlElementAttribute(Type)

Inicializa una nueva instancia de la clase XmlElementAttribute y especifica un tipo de miembro al que XmlElementAttribute es aplicado.Initializes a new instance of the XmlElementAttribute class and specifies a type for the member to which the XmlElementAttribute is applied. Este tipo es utilizado por XmlSerializer al serializar o deserializar el objeto que lo contiene.This type is used by the XmlSerializer when serializing or deserializing object that contains it.

Propiedades

DataType DataType DataType DataType

Obtiene o establece el tipo de datos de la definición de esquemas XML (XSD) del elemento XM1 generado por XmlSerializer.Gets or sets the XML Schema definition (XSD) data type of the XML element generated by the XmlSerializer.

ElementName ElementName ElementName ElementName

Obtiene o establece el nombre del elemento XML generado.Gets or sets the name of the generated XML element.

Form Form Form Form

Obtiene o establece un valor que indica si el elemento está calificado.Gets or sets a value that indicates whether the element is qualified.

IsNullable IsNullable IsNullable IsNullable

Obtiene o establece un valor que indica si XmlSerializer debe serializar un miembro establecido en null como una etiqueta vacía con el atributo xsi:nil establecido en 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

Obtiene o establece el espacio de nombres asignado al elemento XML como resultado de la serialización de la clase.Gets or sets the namespace assigned to the XML element that results when the class is serialized.

Order Order Order Order

Obtiene o establece el orden explícito en el que los elementos son serializados o deserializados.Gets or sets the explicit order in which the elements are serialized or deserialized.

Type Type Type Type

Obtiene o establece el tipo de objeto utilizado para representar el elemento XML.Gets or sets the object type used to represent the XML element.

TypeId TypeId TypeId TypeId

Cuando se implementa en una clase derivada, obtiene un identificador único para este Attribute.When implemented in a derived class, gets a unique identifier for this Attribute.

(Inherited from Attribute)

Métodos

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

Devuelve un valor que indica si esta instancia es igual que un objeto especificado.Returns a value that indicates whether this instance is equal to a specified object.

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

Devuelve el código hash de esta instancia.Returns the hash code for this instance.

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

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

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

Si se reemplaza en una clase derivada, indica si el valor de esta instancia es el valor predeterminado de la clase derivada.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)

Cuando se invalida en una clase derivada, devuelve un valor que indica si esta instancia es igual a un objeto especificado.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()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

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

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Inherited from Object)

Implementaciones de interfaz explícitas

_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)

Asigna un conjunto de nombres a un conjunto correspondiente de identificadores de envío.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)

Obtiene la información de tipos de un objeto, que puede utilizarse para obtener la información de tipos de una interfaz.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)

Recupera el número de interfaces de información de tipo que proporciona un objeto (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)

Proporciona acceso a las propiedades y los métodos expuestos por un objeto.Provides access to properties and methods exposed by an object.

(Inherited from Attribute)

Se aplica a

Consulte también: