XmlElementAttribute Construtores
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Inicializa uma nova instância da XmlElementAttribute classe.
Sobrecargas
| Name | Description |
|---|---|
| XmlElementAttribute() |
Inicializa uma nova instância da XmlElementAttribute classe. |
| 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 é aplicado. Este tipo é usado pelo XmlSerializer quando serializam ou desserializam objetos que o contêm. |
| XmlElementAttribute(String, Type) |
Inicializa uma nova instância do XmlElementAttribute e especifica o nome do elemento XML e um tipo derivado para o membro ao qual o XmlElementAttribute é aplicado. Este 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 XmlElementAttribute classe.
public:
XmlElementAttribute();
public XmlElementAttribute();
Public Sub New ()
Exemplos
O exemplo seguinte 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 seguinte mostra uma classe simples que contém um único campo chamado Vehicles. O exemplo aplica-se ao XmlElementAttribute campo e inclui o elementName parâmetro, instruindo assim o XmlSerializer a gerar elementos XML chamados "Cars" em vez de "Vehicles".
public class Transportation
{
[XmlElement("Cars")]
public string Vehicles;
}
Public Class Transportation
<XmlElement("Cars")> Public Vehicles As String
End Class
Observações
Por defeito, usa XmlSerializer o nome do membro como nome do elemento XML ao serializar uma instância de classe. Por exemplo, um campo com nome Vehicle gera um elemento XML chamado Vehicle. No entanto, se precisares de um elemento diferente, como Cars, passa-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 é aplicado. Este tipo é usado pelo XmlSerializer quando serializam ou desserializam objetos 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 seguinte serializa uma classe nomeada Orchestra que contém um único campo chamado Instruments, que devolve um array de Instrument objetos. Uma segunda classe chamada Brass herda da Instrument classe. O exemplo aplica-se ao XmlElementAttributeInstruments campo e especifica o Brass tipo, permitindo que o Instruments campo aceite Brass objetos. O exemplo também especifica o nome do elemento XML ao definir 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
Observações
Use o type parâmetro para especificar um tipo derivado de uma classe base. Por exemplo, suponha que uma propriedade nomeada MyAnimal devolve um Animal objeto. Queres melhorar o objeto, por isso crias uma nova classe chamada Mammal que herda da Animal classe. Para instruir o XmlSerializer a aceitar a Mammal classe quando serializa a MyAnimal propriedade, passa o Type da Mammal classe ao 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 e especifica o nome do elemento XML e um tipo derivado para o membro ao qual o XmlElementAttribute é aplicado. Este 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 seguinte serializa uma classe nomeada Orchestra que contém um único campo chamado Instruments, que devolve um array de Instrument objetos. Uma segunda classe chamada Brass herda da Instrument classe. O exemplo aplica-se ao XmlElementAttributeInstruments campo e especifica o Brass tipo, permitindo que o Instruments campo aceite Brass objetos. O exemplo também especifica o nome do elemento XML ao definir 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
Observações
Por defeito, usa XmlSerializer o nome do membro como nome do elemento XML ao serializar uma instância de classe. Por exemplo, um campo com nome Vehicle gera um elemento XML chamado Vehicle. No entanto, se precisares de um elemento diferente, como Cars, passa-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 devolve um Animal objeto. Queres melhorar o objeto, por isso crias uma nova classe chamada Mammal que herda da Animal classe. Para instruir o XmlSerializer a aceitar a Mammal classe quando serializa a MyAnimal propriedade, passa o Type da Mammal classe ao construtor.