XmlElementAttribute Construtores
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Inicializa uma nova instância da classe XmlElementAttribute.
Sobrecargas
| Nome | Description |
|---|---|
| XmlElementAttribute() |
Inicializa uma nova instância da classe XmlElementAttribute. |
| XmlElementAttribute(String) |
Inicializa uma nova instância da XmlElementAttribute classe e especifica o nome do elemento XML. |
| XmlElementAttribute(Type) |
Inicializa uma nova instância da XmlElementAttribute classe e especifica um tipo para o membro ao qual o XmlElementAttribute membro é aplicado. Esse tipo é usado pelo XmlSerializer objeto de serialização ou desserialização que o contém. |
| XmlElementAttribute(String, Type) |
Inicializa uma nova instância do XmlElementAttribute elemento XML e especifica o nome do elemento XML e um tipo derivado para o membro ao qual ele XmlElementAttribute é aplicado. Esse tipo de membro é usado quando serializa XmlSerializer o objeto que o contém. |
XmlElementAttribute()
- Origem:
- XmlElementAttribute.cs
- Origem:
- XmlElementAttribute.cs
- Origem:
- XmlElementAttribute.cs
- Origem:
- XmlElementAttribute.cs
- Origem:
- XmlElementAttribute.cs
Inicializa uma nova instância da classe XmlElementAttribute.
public:
XmlElementAttribute();
public XmlElementAttribute();
Public Sub New ()
Exemplos
O exemplo a seguir aplica-se a XmlElementAttribute uma classe.
public class MyClass
{
[XmlElement()]
public string TeacherName;
}
Public Class MyClass1
<XmlElement()> Public TeacherName As String
End Class
Aplica-se a
XmlElementAttribute(String)
- Origem:
- XmlElementAttribute.cs
- Origem:
- XmlElementAttribute.cs
- Origem:
- XmlElementAttribute.cs
- Origem:
- XmlElementAttribute.cs
- Origem:
- XmlElementAttribute.cs
Inicializa uma nova instância da XmlElementAttribute classe e especifica o nome do 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
O nome do elemento XML do membro serializado.
Exemplos
O exemplo a seguir mostra uma classe simples que contém um único campo chamado Vehicles. O exemplo aplica-se XmlElementAttribute ao campo e inclui o elementName parâmetro, instruindo assim a XmlSerializer gerar elementos XML chamados "Carros" em vez de "Veículos".
public class Transportation
{
[XmlElement("Cars")]
public string Vehicles;
}
Public Class Transportation
<XmlElement("Cars")> Public Vehicles As String
End Class
Comentários
Por padrão, o nome do XmlSerializer membro é usado como o nome do elemento XML ao serializar uma instância de classe. Por exemplo, um campo chamado Vehicle gera um elemento XML chamado Vehicle. No entanto, se você precisar de um elemento diferente, como Cars, passe-o no elementName parâmetro.
Aplica-se a
XmlElementAttribute(Type)
- Origem:
- XmlElementAttribute.cs
- Origem:
- XmlElementAttribute.cs
- Origem:
- XmlElementAttribute.cs
- Origem:
- XmlElementAttribute.cs
- Origem:
- XmlElementAttribute.cs
Inicializa uma nova instância da XmlElementAttribute classe e especifica um tipo para o membro ao qual o XmlElementAttribute membro é aplicado. Esse tipo é usado pelo XmlSerializer objeto de serialização ou desserialização que o contém.
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
Exemplos
O exemplo a seguir serializa uma classe nomeada Orchestra que contém um único campo chamado Instruments, que retorna uma matriz de Instrument objetos. Uma segunda classe chamada Brass herda da Instrument classe. O exemplo aplica-se XmlElementAttribute ao Instruments campo e especifica o Brass tipo, permitindo que o Instruments campo aceite Brass objetos. O exemplo também especifica o nome do elemento XML definindo a ElementName propriedade.
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
Comentários
Use o type parâmetro para especificar um tipo derivado de uma classe base. Por exemplo, suponha que uma propriedade nomeada MyAnimal retorne um Animal objeto. Você deseja aprimorar o objeto para criar uma nova classe chamada Mammal que herda da Animal classe. Para instruir a XmlSerializer classe a aceitar Mammal quando serializar a MyAnimal propriedade, passe a TypeMammal classe para o construtor.
Aplica-se a
XmlElementAttribute(String, Type)
- Origem:
- XmlElementAttribute.cs
- Origem:
- XmlElementAttribute.cs
- Origem:
- XmlElementAttribute.cs
- Origem:
- XmlElementAttribute.cs
- Origem:
- XmlElementAttribute.cs
Inicializa uma nova instância do XmlElementAttribute elemento XML e especifica o nome do elemento XML e um tipo derivado para o membro ao qual ele XmlElementAttribute é aplicado. Esse tipo de membro é usado quando serializa XmlSerializer o objeto que o contém.
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
O nome do elemento XML do membro serializado.
Exemplos
O exemplo a seguir serializa uma classe nomeada Orchestra que contém um único campo chamado Instruments, que retorna uma matriz de Instrument objetos. Uma segunda classe chamada Brass herda da Instrument classe. O exemplo aplica-se XmlElementAttribute ao Instruments campo e especifica o Brass tipo, permitindo que o Instruments campo aceite Brass objetos. O exemplo também especifica o nome do elemento XML definindo a ElementName propriedade.
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
Comentários
Por padrão, o nome do XmlSerializer membro é usado como o nome do elemento XML ao serializar uma instância de classe. Por exemplo, um campo chamado Vehicle gera um elemento XML chamado Vehicle. No entanto, se você precisar de um elemento diferente, como Cars, passe-o no elementName parâmetro.
Use o type parâmetro para especificar um tipo derivado de uma classe base. Por exemplo, suponha que uma propriedade nomeada MyAnimal retorne um Animal objeto. Você deseja aprimorar o objeto para criar uma nova classe chamada Mammal que herda da Animal classe. Para instruir a XmlSerializer classe a aceitar Mammal quando serializar a MyAnimal propriedade, passe a TypeMammal classe para o construtor.