XmlElementAttribute Конструкторы
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Инициализирует новый экземпляр класса XmlElementAttribute.
Перегрузки
| Имя | Описание |
|---|---|
| XmlElementAttribute() |
Инициализирует новый экземпляр класса XmlElementAttribute. |
| XmlElementAttribute(String) |
Инициализирует новый экземпляр XmlElementAttribute класса и задает имя XML-элемента. |
| XmlElementAttribute(Type) |
Инициализирует новый экземпляр XmlElementAttribute класса и задает тип элемента, к которому применяется.XmlElementAttribute Этот тип используется XmlSerializer при сериализации или десериализации объекта, содержащего его. |
| XmlElementAttribute(String, Type) |
Инициализирует новый экземпляр XmlElementAttribute и задает имя XML-элемента и производный тип элемента, к которому XmlElementAttribute применяется. Этот тип элемента используется при XmlSerializer сериализации объекта, содержащего его. |
XmlElementAttribute()
- Исходный код:
- XmlElementAttribute.cs
- Исходный код:
- XmlElementAttribute.cs
- Исходный код:
- XmlElementAttribute.cs
- Исходный код:
- XmlElementAttribute.cs
- Исходный код:
- XmlElementAttribute.cs
Инициализирует новый экземпляр класса XmlElementAttribute.
public:
XmlElementAttribute();
public XmlElementAttribute();
Public Sub New ()
Примеры
В следующем примере применяется к классу XmlElementAttribute .
public class MyClass
{
[XmlElement()]
public string TeacherName;
}
Public Class MyClass1
<XmlElement()> Public TeacherName As String
End Class
Применяется к
XmlElementAttribute(String)
- Исходный код:
- XmlElementAttribute.cs
- Исходный код:
- XmlElementAttribute.cs
- Исходный код:
- XmlElementAttribute.cs
- Исходный код:
- XmlElementAttribute.cs
- Исходный код:
- XmlElementAttribute.cs
Инициализирует новый экземпляр XmlElementAttribute класса и задает имя 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)
Параметры
- elementName
- String
Имя XML-элемента сериализованного элемента.
Примеры
В следующем примере показан простой класс, содержащий одно поле с именем Vehicles. В этом примере применяется XmlElementAttribute к полю и включается elementName параметр, что позволяет XmlSerializer создавать XML-элементы с именем "Автомобили", а не "Автомобили".
public class Transportation
{
[XmlElement("Cars")]
public string Vehicles;
}
Public Class Transportation
<XmlElement("Cars")> Public Vehicles As String
End Class
Комментарии
По умолчанию XmlSerializer имя члена используется в качестве имени XML-элемента при сериализации экземпляра класса. Например, поле с именем Vehicle создает XML-элемент с именем Vehicle. Однако если вам нужен другой элемент, например Cars, передайте его в elementName параметр.
Применяется к
XmlElementAttribute(Type)
- Исходный код:
- XmlElementAttribute.cs
- Исходный код:
- XmlElementAttribute.cs
- Исходный код:
- XmlElementAttribute.cs
- Исходный код:
- XmlElementAttribute.cs
- Исходный код:
- XmlElementAttribute.cs
Инициализирует новый экземпляр XmlElementAttribute класса и задает тип элемента, к которому применяется.XmlElementAttribute Этот тип используется XmlSerializer при сериализации или десериализации объекта, содержащего его.
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)
Параметры
Примеры
В следующем примере сериализуется класс с именем Orchestra , который содержит одно поле с именем Instruments, которое возвращает массив Instrument объектов. Второй класс с именем Brass наследует от Instrument класса. В примере применяется XmlElementAttribute к Instruments полю и указывается Brass тип, позволяющий Instruments полю принимать Brass объекты. В примере также указывается имя XML-элемента, задав ElementName свойство.
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
Комментарии
type Используйте параметр, чтобы указать тип, производный от базового класса. Например, предположим, что свойство с именем MyAnimal возвращает Animal объект. Вы хотите улучшить объект, поэтому вы создадите новый класс с именем Mammal , наследуемым от Animal класса. Чтобы указать XmlSerializer , что класс принимается Mammal при сериализации MyAnimal свойства, передайте TypeMammal класс конструктору.
Применяется к
XmlElementAttribute(String, Type)
- Исходный код:
- XmlElementAttribute.cs
- Исходный код:
- XmlElementAttribute.cs
- Исходный код:
- XmlElementAttribute.cs
- Исходный код:
- XmlElementAttribute.cs
- Исходный код:
- XmlElementAttribute.cs
Инициализирует новый экземпляр XmlElementAttribute и задает имя XML-элемента и производный тип элемента, к которому XmlElementAttribute применяется. Этот тип элемента используется при XmlSerializer сериализации объекта, содержащего его.
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)
Параметры
- elementName
- String
Имя XML-элемента сериализованного элемента.
Примеры
В следующем примере сериализуется класс с именем Orchestra , который содержит одно поле с именем Instruments, которое возвращает массив Instrument объектов. Второй класс с именем Brass наследует от Instrument класса. В примере применяется XmlElementAttribute к Instruments полю и указывается Brass тип, позволяющий Instruments полю принимать Brass объекты. В примере также указывается имя XML-элемента, задав ElementName свойство.
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
Комментарии
По умолчанию XmlSerializer имя члена используется в качестве имени XML-элемента при сериализации экземпляра класса. Например, поле с именем Vehicle создает XML-элемент с именем Vehicle. Однако, если вам нужен другой элемент, например Cars, передайте его в elementName параметр.
type Используйте параметр, чтобы указать тип, производный от базового класса. Например, предположим, что свойство с именем MyAnimal возвращает Animal объект. Вы хотите улучшить объект, поэтому вы создадите новый класс с именем Mammal , наследуемым от Animal класса. Чтобы указать XmlSerializer , что класс принимается Mammal при сериализации MyAnimal свойства, передайте TypeMammal класс конструктору.