XmlElementAttribute Constructores

Definición

Inicializa una nueva instancia de la clase XmlElementAttribute.

Sobrecargas

XmlElementAttribute()

Inicializa una nueva instancia de la clase XmlElementAttribute.

XmlElementAttribute(String)

Inicializa una nueva instancia de la clase XmlElementAttribute y especifica el nombre del elemento XML.

XmlElementAttribute(Type)

Inicializa una nueva instancia de la clase XmlElementAttribute y especifica un tipo de miembro al que XmlElementAttribute es aplicado. Este tipo es utilizado por XmlSerializer al serializar o deserializar el objeto que lo contiene.

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. Este tipo de miembro se utiliza cuando XmlSerializer serializa el objeto que lo contiene.

XmlElementAttribute()

Inicializa una nueva instancia de la clase XmlElementAttribute.

public:
 XmlElementAttribute();
public XmlElementAttribute ();
Public Sub New ()

Ejemplos

En el ejemplo siguiente se aplica a XmlElementAttribute una clase .

public ref class MyClass
{
public:

   [XmlElement]
   String^ TeacherName;
};
public class MyClass
{
   [XmlElement()]
   public string TeacherName;
}
Public Class MyClass1
    <XmlElement()> Public TeacherName As String
End Class

Se aplica a

XmlElementAttribute(String)

Inicializa una nueva instancia de la clase XmlElementAttribute y especifica el nombre del elemento XML.

public:
 XmlElementAttribute(System::String ^ elementName);
public XmlElementAttribute (string elementName);
public XmlElementAttribute (string? elementName);
new System.Xml.Serialization.XmlElementAttribute : string -> System.Xml.Serialization.XmlElementAttribute
Public Sub New (elementName As String)

Parámetros

elementName
String

Nombre de elemento XML del miembro serializado.

Ejemplos

En el ejemplo siguiente se muestra una clase simple que contiene un único campo denominado Vehicles. El ejemplo aplica al XmlElementAttribute campo e incluye el elementName parámetro , lo que indica a que XmlSerializer genere elementos XML denominados "Cars" en lugar de "Vehículos".

public ref class Transportation
{
public:

   [XmlElement("Cars")]
   String^ Vehicles;
};
public class Transportation
{
   [XmlElement("Cars")]
   public string Vehicles;
}
Public Class Transportation
    <XmlElement("Cars")> Public Vehicles As String
End Class

Comentarios

De forma predeterminada, XmlSerializer usa el nombre de miembro como nombre del elemento XML al serializar una instancia de clase. Por ejemplo, un campo denominado Vehicle genera un elemento XML denominado Vehicle. Sin embargo, si necesita un elemento diferente, como Cars, páselo en el elementName parámetro .

Se aplica a

XmlElementAttribute(Type)

Inicializa una nueva instancia de la clase XmlElementAttribute y especifica un tipo de miembro al que XmlElementAttribute es aplicado. Este tipo es utilizado por XmlSerializer al serializar o deserializar el objeto que lo contiene.

public:
 XmlElementAttribute(Type ^ type);
public XmlElementAttribute (Type type);
public XmlElementAttribute (Type? type);
new System.Xml.Serialization.XmlElementAttribute : Type -> System.Xml.Serialization.XmlElementAttribute
Public Sub New (type As Type)

Parámetros

type
Type

Type de un objeto derivado del tipo de miembro.

Ejemplos

El siguiente ejemplo serializa una clase denominada Orchestra que contiene un solo campo denominado Instruments, que devuelve una matriz de Instrument objetos. Una segunda clase denominada Brass hereda de la Instrument clase . En el ejemplo se aplica al XmlElementAttribute Instruments campo y se especifica el Brass tipo , lo que permite que el Instruments campo acepte Brass objetos. En el ejemplo también se especifica el nombre del elemento XML estableciendo la ElementName propiedad .

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

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

public ref class Brass: public Instrument
{
public:
   bool IsValved;
};

public ref class Orchestra
{
public:
   array<Instrument^>^Instruments;
};

void SerializeObject( String^ filename )
{
   // To write the file, a TextWriter is required.
   TextWriter^ writer = gcnew StreamWriter( filename );
   XmlAttributeOverrides^ attrOverrides = gcnew XmlAttributeOverrides;
   XmlAttributes^ attrs = gcnew XmlAttributes;

   // Creates an XmlElementAttribute that overrides the Instrument type.
   XmlElementAttribute^ attr = gcnew XmlElementAttribute( Brass::typeid );
   attr->ElementName = "Brass";

   // Adds the element to the collection of elements.
   attrs->XmlElements->Add( attr );
   attrOverrides->Add( Orchestra::typeid, "Instruments", attrs );

   // Creates the XmlSerializer using the XmlAttributeOverrides.
   XmlSerializer^ s = gcnew XmlSerializer( Orchestra::typeid,attrOverrides );

   // Creates the object to serialize.
   Orchestra^ band = gcnew Orchestra;

   // Creates an object of the derived type.
   Brass^ i = gcnew Brass;
   i->Name = "Trumpet";
   i->IsValved = true;
   array<Instrument^>^myInstruments = {i};
   band->Instruments = myInstruments;
   s->Serialize( writer, band );
   writer->Close();
}

void DeserializeObject( String^ filename )
{
   XmlAttributeOverrides^ attrOverrides = gcnew XmlAttributeOverrides;
   XmlAttributes^ attrs = gcnew XmlAttributes;

   // Creates an XmlElementAttribute that override the Instrument type.
   XmlElementAttribute^ attr = gcnew XmlElementAttribute( Brass::typeid );
   attr->ElementName = "Brass";

   // Adds the element to the collection of elements.
   attrs->XmlElements->Add( attr );
   attrOverrides->Add( Orchestra::typeid, "Instruments", attrs );

   // Creates the XmlSerializer using the XmlAttributeOverrides.
   XmlSerializer^ s = gcnew XmlSerializer( Orchestra::typeid,attrOverrides );
   FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
   Orchestra^ band = dynamic_cast<Orchestra^>(s->Deserialize( fs ));
   Console::WriteLine( "Brass:" );

   /* Deserializing differs from serializing. To read the 
      derived-object values, declare an object of the derived 
      type (Brass) and cast the Instrument instance to it. */
   Brass^ b;
   System::Collections::IEnumerator^ myEnum = band->Instruments->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Instrument^ i = safe_cast<Instrument^>(myEnum->Current);
      b = dynamic_cast<Brass^>(i);
      Console::WriteLine( "{0}\n{1}", b->Name, b->IsValved );
   }
}

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

public class Orchestra
{
   public Instrument[] Instruments;
}

public class Instrument
{
   public string Name;
}

public class Brass:Instrument{
   public bool IsValved;
}

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

    public void SerializeObject(string filename)
    {
      // To write the file, a TextWriter is required.
      TextWriter writer = new StreamWriter(filename);

      XmlAttributeOverrides attrOverrides =
         new XmlAttributeOverrides();
      XmlAttributes attrs = new XmlAttributes();

      // Creates an XmlElementAttribute that overrides the Instrument type.
      XmlElementAttribute attr = new
      XmlElementAttribute(typeof(Brass));
      attr.ElementName = "Brass";

      // Adds the element to the collection of elements.
      attrs.XmlElements.Add(attr);
      attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);

      // Creates the XmlSerializer using the XmlAttributeOverrides.
      XmlSerializer s =
      new XmlSerializer(typeof(Orchestra), attrOverrides);

      // Creates the object to serialize.
      Orchestra band = new Orchestra();

      // Creates an object of the derived type.
      Brass i = new Brass();
      i.Name = "Trumpet";
      i.IsValved = true;
      Instrument[] myInstruments = {i};
      band.Instruments = myInstruments;
      s.Serialize(writer,band);
      writer.Close();
   }

   public void DeserializeObject(string filename)
   {
      XmlAttributeOverrides attrOverrides =
         new XmlAttributeOverrides();
      XmlAttributes attrs = new XmlAttributes();

      // Creates an XmlElementAttribute that override the Instrument type.
      XmlElementAttribute attr = new
      XmlElementAttribute(typeof(Brass));
      attr.ElementName = "Brass";

      // Adds the element to the collection of elements.
      attrs.XmlElements.Add(attr);
      attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);

      // Creates the XmlSerializer using the XmlAttributeOverrides.
      XmlSerializer s =
      new XmlSerializer(typeof(Orchestra), attrOverrides);

      FileStream fs = new FileStream(filename, FileMode.Open);
      Orchestra band = (Orchestra) s.Deserialize(fs);
      Console.WriteLine("Brass:");

      /* Deserializing differs from serializing. To read the
         derived-object values, declare an object of the derived
         type (Brass) and cast the Instrument instance to it. */
      Brass b;
      foreach(Instrument i in band.Instruments)
      {
         b= (Brass)i;
         Console.WriteLine(
         b.Name + "\n" +
         b.IsValved);
      }
   }
}
Option Strict
Option Explicit

Imports System.IO
Imports System.Xml.Serialization

Public Class Orchestra
    Public Instruments() As Instrument
End Class

Public Class Instrument
    Public Name As String
End Class

Public Class Brass
    Inherits Instrument
    Public IsValved As Boolean
End Class

Public Class Run
    
    Public Shared Sub Main()
        Dim test As New Run()
        test.SerializeObject("Override.xml")
        test.DeserializeObject("Override.xml")
    End Sub
    
    
    Public Sub SerializeObject(filename As String)
        ' To write the file, a TextWriter is required.
        Dim writer As New StreamWriter(filename)
        
        Dim attrOverrides As New XmlAttributeOverrides()
        Dim attrs As New XmlAttributes()
        
        ' Creates an XmlElementAttribute that overrides the Instrument type.
        Dim attr As New XmlElementAttribute(GetType(Brass))
        attr.ElementName = "Brass"
        
        ' Adds the element to the collection of elements.
        attrs.XmlElements.Add(attr)
        attrOverrides.Add(GetType(Orchestra), "Instruments", attrs)
        
        ' Creates the XmlSerializer using the XmlAttributeOverrides.
        Dim s As New XmlSerializer(GetType(Orchestra), attrOverrides)
        
        ' Creates the object to serialize.
        Dim band As New Orchestra()
        
        ' Creates an object of the derived type.
        Dim i As New Brass()
        i.Name = "Trumpet"
        i.IsValved = True
        Dim myInstruments() As Instrument = {i}
        band.Instruments = myInstruments
        s.Serialize(writer, band)
        writer.Close()
    End Sub
    
    
    Public Sub DeserializeObject(filename As String)
        Dim attrOverrides As New XmlAttributeOverrides()
        Dim attrs As New XmlAttributes()
        
        ' Create an XmlElementAttribute that override the Instrument type.
        Dim attr As New XmlElementAttribute(GetType(Brass))
        attr.ElementName = "Brass"
        
        ' Add the element to the collection of elements.
        attrs.XmlElements.Add(attr)
        attrOverrides.Add(GetType(Orchestra), "Instruments", attrs)
        
        ' Create the XmlSerializer using the XmlAttributeOverrides.
        Dim s As New XmlSerializer(GetType(Orchestra), attrOverrides)
        
        Dim fs As New FileStream(filename, FileMode.Open)
        Dim band As Orchestra = CType(s.Deserialize(fs), Orchestra)
        Console.WriteLine("Brass:")
        
        ' Deserializing differs from serializing. To read the
        ' derived-object values, declare an object of the derived
        ' type (Brass) and cast the Instrument instance to it. 
        Dim b As Brass
        Dim i As Instrument
        For Each i In  band.Instruments
            b = CType(i, Brass)
            Console.WriteLine((b.Name + ControlChars.Cr + b.IsValved.ToString()))
        Next i
    End Sub
End Class

Comentarios

Use el type parámetro para especificar un tipo derivado de una clase base. Por ejemplo, supongamos que una propiedad denominada MyAnimal devuelve un Animal objeto. Quiere mejorar el objeto, por lo que se crea una nueva clase denominada Mammal que hereda de la Animal clase . Para indicar el XmlSerializer para aceptar el Mammal clase cuando serializa el MyAnimal propiedad, pase el Type de la Mammal clase al constructor.

Se aplica a

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. Este tipo de miembro se utiliza cuando XmlSerializer serializa el objeto que lo contiene.

public:
 XmlElementAttribute(System::String ^ elementName, Type ^ type);
public XmlElementAttribute (string elementName, Type type);
public XmlElementAttribute (string? elementName, Type? type);
new System.Xml.Serialization.XmlElementAttribute : string * Type -> System.Xml.Serialization.XmlElementAttribute
Public Sub New (elementName As String, type As Type)

Parámetros

elementName
String

Nombre de elemento XML del miembro serializado.

type
Type

Type de un objeto derivado del tipo de miembro.

Ejemplos

El siguiente ejemplo serializa una clase denominada Orchestra que contiene un solo campo denominado Instruments, que devuelve una matriz de Instrument objetos. Una segunda clase denominada Brass hereda de la Instrument clase . En el ejemplo se aplica al XmlElementAttribute Instruments campo y se especifica el Brass tipo , lo que permite que el Instruments campo acepte Brass objetos. En el ejemplo también se especifica el nombre del elemento XML estableciendo la ElementName propiedad .

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

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

public ref class Brass: public Instrument
{
public:
   bool IsValved;
};

public ref class Orchestra
{
public:
   array<Instrument^>^Instruments;
};

void SerializeObject( String^ filename )
{
   // To write the file, a TextWriter is required.
   TextWriter^ writer = gcnew StreamWriter( filename );
   XmlAttributeOverrides^ attrOverrides = gcnew XmlAttributeOverrides;
   XmlAttributes^ attrs = gcnew XmlAttributes;

   // Creates an XmlElementAttribute that overrides the Instrument type.
   XmlElementAttribute^ attr = gcnew XmlElementAttribute( Brass::typeid );
   attr->ElementName = "Brass";

   // Adds the element to the collection of elements.
   attrs->XmlElements->Add( attr );
   attrOverrides->Add( Orchestra::typeid, "Instruments", attrs );

   // Creates the XmlSerializer using the XmlAttributeOverrides.
   XmlSerializer^ s = gcnew XmlSerializer( Orchestra::typeid,attrOverrides );

   // Creates the object to serialize.
   Orchestra^ band = gcnew Orchestra;

   // Creates an object of the derived type.
   Brass^ i = gcnew Brass;
   i->Name = "Trumpet";
   i->IsValved = true;
   array<Instrument^>^myInstruments = {i};
   band->Instruments = myInstruments;
   s->Serialize( writer, band );
   writer->Close();
}

void DeserializeObject( String^ filename )
{
   XmlAttributeOverrides^ attrOverrides = gcnew XmlAttributeOverrides;
   XmlAttributes^ attrs = gcnew XmlAttributes;

   // Creates an XmlElementAttribute that override the Instrument type.
   XmlElementAttribute^ attr = gcnew XmlElementAttribute( Brass::typeid );
   attr->ElementName = "Brass";

   // Adds the element to the collection of elements.
   attrs->XmlElements->Add( attr );
   attrOverrides->Add( Orchestra::typeid, "Instruments", attrs );

   // Creates the XmlSerializer using the XmlAttributeOverrides.
   XmlSerializer^ s = gcnew XmlSerializer( Orchestra::typeid,attrOverrides );
   FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
   Orchestra^ band = dynamic_cast<Orchestra^>(s->Deserialize( fs ));
   Console::WriteLine( "Brass:" );

   /* Deserializing differs from serializing. To read the 
      derived-object values, declare an object of the derived 
      type (Brass) and cast the Instrument instance to it. */
   Brass^ b;
   System::Collections::IEnumerator^ myEnum = band->Instruments->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Instrument^ i = safe_cast<Instrument^>(myEnum->Current);
      b = dynamic_cast<Brass^>(i);
      Console::WriteLine( "{0}\n{1}", b->Name, b->IsValved );
   }
}

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

public class Orchestra
{
   public Instrument[] Instruments;
}

public class Instrument
{
   public string Name;
}

public class Brass:Instrument{
   public bool IsValved;
}

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

    public void SerializeObject(string filename)
    {
      // To write the file, a TextWriter is required.
      TextWriter writer = new StreamWriter(filename);

      XmlAttributeOverrides attrOverrides =
         new XmlAttributeOverrides();
      XmlAttributes attrs = new XmlAttributes();

      // Creates an XmlElementAttribute that overrides the Instrument type.
      XmlElementAttribute attr = new
      XmlElementAttribute(typeof(Brass));
      attr.ElementName = "Brass";

      // Adds the element to the collection of elements.
      attrs.XmlElements.Add(attr);
      attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);

      // Creates the XmlSerializer using the XmlAttributeOverrides.
      XmlSerializer s =
      new XmlSerializer(typeof(Orchestra), attrOverrides);

      // Creates the object to serialize.
      Orchestra band = new Orchestra();

      // Creates an object of the derived type.
      Brass i = new Brass();
      i.Name = "Trumpet";
      i.IsValved = true;
      Instrument[] myInstruments = {i};
      band.Instruments = myInstruments;
      s.Serialize(writer,band);
      writer.Close();
   }

   public void DeserializeObject(string filename)
   {
      XmlAttributeOverrides attrOverrides =
         new XmlAttributeOverrides();
      XmlAttributes attrs = new XmlAttributes();

      // Creates an XmlElementAttribute that override the Instrument type.
      XmlElementAttribute attr = new
      XmlElementAttribute(typeof(Brass));
      attr.ElementName = "Brass";

      // Adds the element to the collection of elements.
      attrs.XmlElements.Add(attr);
      attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);

      // Creates the XmlSerializer using the XmlAttributeOverrides.
      XmlSerializer s =
      new XmlSerializer(typeof(Orchestra), attrOverrides);

      FileStream fs = new FileStream(filename, FileMode.Open);
      Orchestra band = (Orchestra) s.Deserialize(fs);
      Console.WriteLine("Brass:");

      /* Deserializing differs from serializing. To read the
         derived-object values, declare an object of the derived
         type (Brass) and cast the Instrument instance to it. */
      Brass b;
      foreach(Instrument i in band.Instruments)
      {
         b= (Brass)i;
         Console.WriteLine(
         b.Name + "\n" +
         b.IsValved);
      }
   }
}
Option Strict
Option Explicit

Imports System.IO
Imports System.Xml.Serialization

Public Class Orchestra
    Public Instruments() As Instrument
End Class

Public Class Instrument
    Public Name As String
End Class

Public Class Brass
    Inherits Instrument
    Public IsValved As Boolean
End Class

Public Class Run
    
    Public Shared Sub Main()
        Dim test As New Run()
        test.SerializeObject("Override.xml")
        test.DeserializeObject("Override.xml")
    End Sub
    
    
    Public Sub SerializeObject(filename As String)
        ' To write the file, a TextWriter is required.
        Dim writer As New StreamWriter(filename)
        
        Dim attrOverrides As New XmlAttributeOverrides()
        Dim attrs As New XmlAttributes()
        
        ' Creates an XmlElementAttribute that overrides the Instrument type.
        Dim attr As New XmlElementAttribute(GetType(Brass))
        attr.ElementName = "Brass"
        
        ' Adds the element to the collection of elements.
        attrs.XmlElements.Add(attr)
        attrOverrides.Add(GetType(Orchestra), "Instruments", attrs)
        
        ' Creates the XmlSerializer using the XmlAttributeOverrides.
        Dim s As New XmlSerializer(GetType(Orchestra), attrOverrides)
        
        ' Creates the object to serialize.
        Dim band As New Orchestra()
        
        ' Creates an object of the derived type.
        Dim i As New Brass()
        i.Name = "Trumpet"
        i.IsValved = True
        Dim myInstruments() As Instrument = {i}
        band.Instruments = myInstruments
        s.Serialize(writer, band)
        writer.Close()
    End Sub
    
    
    Public Sub DeserializeObject(filename As String)
        Dim attrOverrides As New XmlAttributeOverrides()
        Dim attrs As New XmlAttributes()
        
        ' Create an XmlElementAttribute that override the Instrument type.
        Dim attr As New XmlElementAttribute(GetType(Brass))
        attr.ElementName = "Brass"
        
        ' Add the element to the collection of elements.
        attrs.XmlElements.Add(attr)
        attrOverrides.Add(GetType(Orchestra), "Instruments", attrs)
        
        ' Create the XmlSerializer using the XmlAttributeOverrides.
        Dim s As New XmlSerializer(GetType(Orchestra), attrOverrides)
        
        Dim fs As New FileStream(filename, FileMode.Open)
        Dim band As Orchestra = CType(s.Deserialize(fs), Orchestra)
        Console.WriteLine("Brass:")
        
        ' Deserializing differs from serializing. To read the
        ' derived-object values, declare an object of the derived
        ' type (Brass) and cast the Instrument instance to it. 
        Dim b As Brass
        Dim i As Instrument
        For Each i In  band.Instruments
            b = CType(i, Brass)
            Console.WriteLine((b.Name + ControlChars.Cr + b.IsValved.ToString()))
        Next i
    End Sub
End Class

Comentarios

De forma predeterminada, XmlSerializer usa el nombre de miembro como nombre del elemento XML al serializar una instancia de clase. Por ejemplo, un campo denominado Vehicle genera un elemento XML denominado Vehicle. Sin embargo, si necesita un elemento diferente, como Cars, páselo en el elementName parámetro .

Use el type parámetro para especificar un tipo derivado de una clase base. Por ejemplo, supongamos que una propiedad denominada MyAnimal devuelve un Animal objeto. Quiere mejorar el objeto, por lo que se crea una nueva clase denominada Mammal que hereda de la Animal clase . Para indicar el XmlSerializer para aceptar el Mammal clase cuando serializa el MyAnimal propiedad, pase el Type de la Mammal clase al constructor.

Se aplica a