XmlElementAttribute Klasa

Definicja

Wskazuje, że pole publiczne lub właściwość reprezentuje element XML, gdy XmlSerializer serializuje lub deserializuje obiekt, który go zawiera.

public ref class XmlElementAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.ReturnValue, AllowMultiple=true)]
public class XmlElementAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.ReturnValue, AllowMultiple=true)>]
type XmlElementAttribute = class
    inherit Attribute
Public Class XmlElementAttribute
Inherits Attribute
Dziedziczenie
XmlElementAttribute
Atrybuty

Przykłady

Poniższy przykład serializuje klasę o nazwie Group i stosuje element XmlElementAttribute do kilku jego składowych. Pole o nazwie Employees zwraca tablicę Employee obiektów. W takim przypadku określa, XmlElementAttribute że wynikowy kod XML nie zostanie zagnieżdżony (co jest domyślnym zachowaniem elementów w tablicy).

#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.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

Uwagi

Element XmlElementAttribute należy do rodziny atrybutów, które kontrolują sposób XmlSerializer serializacji lub deserializacji obiektu. Aby uzyskać pełną listę podobnych atrybutów, zobacz Atrybuty, które kontrolują serializacji XML.

Dokument XML zwykle zawiera elementy XML, z których każdy składa się z trzech części: tag otwierający z możliwymi atrybutami, tagiem zamykającym i danymi między tagami. Tagi XML można zagnieżdżać — czyli dane między tagami mogą być również elementami XML. Ta pojemność jednego elementu do ujęć w inny pozwala dokumentowi zawierać hierarchie danych. Element XML może również zawierać atrybuty.

Zastosuj właściwość XmlElementAttribute do pól publicznych lub publicznych właściwości odczytu/zapisu, aby kontrolować charakterystykę elementów XML, takich jak nazwa elementu i przestrzeń nazw.

Obiekt XmlElementAttribute można wielokrotnie stosować do pola zwracającego tablicę obiektów. Celem tego jest określenie (za pośrednictwem Type właściwości) różnych typów, które można wstawić do tablicy. Na przykład tablica w poniższym kodzie języka C# akceptuje zarówno ciągi, jak i liczby całkowite.

public class Things{  
   [XmlElement(Type = typeof(string)),  
   XmlElement(Type = typeof(int))]  
   public object[] StringsAndInts;  
}  

Spowoduje to wyświetlenie kodu XML, który może wyglądać podobnie do poniższego.

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

Należy pamiętać, że w przypadku wielokrotnego XmlElementAttribute ElementName stosowania wartości właściwości elementy są nazwane po typie akceptowalnych obiektów.

Jeśli zastosujesz XmlElementAttribute element do pola lub właściwości zwracającej tablicę, elementy w tablicy są kodowane jako sekwencja elementów XML.

W przeciwieństwie do tego, jeśli element XmlElementAttribute nie jest stosowany do takiego pola lub właściwości, elementy w tablicy są kodowane jako sekwencja elementów zagnieżdżonych pod elementem o nazwie po polu lub właściwości. (Użyj XmlArrayAttribute atrybutów i XmlArrayItemAttribute , aby kontrolować sposób serializacji tablicy).

Właściwość można ustawić Type tak, aby określić typ, który pochodzi z typu oryginalnego pola lub właściwości — czyli pola lub właściwości, do którego zastosowano XmlElementAttributewłaściwość .

Jeśli pole lub właściwość zwraca ArrayListwartość , można zastosować wiele wystąpień elementu XmlElementAttribute członkowskiego. Dla każdego wystąpienia ustaw Type właściwość na typ obiektu, który można wstawić do tablicy.

Aby uzyskać więcej informacji na temat używania atrybutów, zobacz Atrybuty.

Uwaga

Możesz użyć słowa XmlElement w kodzie zamiast dłuższego XmlElementAttribute.

Konstruktory

XmlElementAttribute()

Inicjuje nowe wystąpienie klasy XmlElementAttribute.

XmlElementAttribute(String)

Inicjuje XmlElementAttribute nowe wystąpienie klasy i określa nazwę elementu XML.

XmlElementAttribute(String, Type)

Inicjuje XmlElementAttribute nowe wystąpienie elementu i określa nazwę elementu XML i typ pochodny dla elementu członkowskiego, do którego XmlElementAttribute jest stosowany. Ten typ elementu członkowskiego jest używany, gdy XmlSerializer serializuje obiekt, który go zawiera.

XmlElementAttribute(Type)

Inicjuje XmlElementAttribute nowe wystąpienie klasy i określa typ elementu członkowskiego, do którego XmlElementAttribute jest stosowany. Ten typ jest używany przez XmlSerializer obiekt podczas serializacji lub deserializacji, który go zawiera.

Właściwości

DataType

Pobiera lub ustawia typ danych definicji schematu XML (XSD) elementu XML wygenerowanego XmlSerializerprzez element .

ElementName

Pobiera lub ustawia nazwę wygenerowanego elementu XML.

Form

Pobiera lub ustawia wartość wskazującą, czy element jest kwalifikowany.

IsNullable

Pobiera lub ustawia wartość wskazującą, czy XmlSerializer element członkowski musi serializować element członkowski ustawiony null na jako pusty tag z atrybutem ustawionym xsi:nil na truewartość .

Namespace

Pobiera lub ustawia przestrzeń nazw przypisaną do elementu XML, który jest wynikiem serializacji klasy.

Order

Pobiera lub ustawia jawną kolejność, w której elementy są serializowane lub deserializowane.

Type

Pobiera lub ustawia typ obiektu używany do reprezentowania elementu XML.

TypeId

Po zaimplementowaniu w klasie pochodnej pobiera unikatowy identyfikator dla tego Attributeelementu .

(Odziedziczone po Attribute)

Metody

Equals(Object)

Zwraca wartość wskazującą, czy to wystąpienie jest równe podanemu obiektowi.

(Odziedziczone po Attribute)
GetHashCode()

Zwraca wartość skrótu dla tego wystąpienia.

(Odziedziczone po Attribute)
GetType()

Type Pobiera wartość bieżącego wystąpienia.

(Odziedziczone po Object)
IsDefaultAttribute()

W przypadku zastąpienia w klasie pochodnej wskazuje, czy wartość tego wystąpienia jest wartością domyślną klasy pochodnej.

(Odziedziczone po Attribute)
Match(Object)

Po przesłonięciu w klasie pochodnej zwraca wartość wskazującą, czy to wystąpienie jest równe określonemu obiektowi.

(Odziedziczone po Attribute)
MemberwiseClone()

Tworzy płytkią kopię bieżącego Objectelementu .

(Odziedziczone po Object)
ToString()

Zwraca ciąg reprezentujący bieżący obiekt.

(Odziedziczone po Object)

Jawne implementacje interfejsu

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Zestaw nazw jest mapowany na odpowiedni zestaw identyfikatorów wysyłania.

(Odziedziczone po Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Pobiera informacje o typie dla obiektu, który może służyć do pobierania informacji o typie dla interfejsu.

(Odziedziczone po Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Pobiera informację o liczbie typów interfejsów, jakie zawiera obiekt (0 lub 1).

(Odziedziczone po Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Umożliwia dostęp do właściwości i metod udostępnianych przez obiekt.

(Odziedziczone po Attribute)

Dotyczy

Zobacz też