Classe XmlElementAttribute (System.Xml.Serialization)

Cambia visualizzazione:
ScriptFree
Riferimento a .NET Framework
Classe XmlElementAttribute

Indica che una proprietà o un campo public rappresenta un elemento XML quando XmlSerializer serializza o deserializza l'oggetto in cui è contenuto.

Spazio dei nomi: System.Xml.Serialization
Assembly: System.Xml (in system.xml.dll)

Sintassi

Visual Basic - (Dichiarazione)
<AttributeUsageAttribute(AttributeTargets.Property Or AttributeTargets.Field Or AttributeTargets.Parameter Or AttributeTargets.ReturnValue, AllowMultiple:=True)> _
Public Class XmlElementAttribute
	Inherits Attribute
Visual Basic (Utilizzo)
Dim instance As XmlElementAttribute

C#
[AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field|AttributeTargets.Parameter|AttributeTargets.ReturnValue, AllowMultiple=true)] 
public class XmlElementAttribute : Attribute
C++
[AttributeUsageAttribute(AttributeTargets::Property|AttributeTargets::Field|AttributeTargets::Parameter|AttributeTargets::ReturnValue, AllowMultiple=true)] 
public ref class XmlElementAttribute : public Attribute
J#
/** @attribute AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field|AttributeTargets.Parameter|AttributeTargets.ReturnValue, AllowMultiple=true) */ 
public class XmlElementAttribute extends Attribute
JScript
AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field|AttributeTargets.Parameter|AttributeTargets.ReturnValue, AllowMultiple=true) 
public class XmlElementAttribute extends Attribute
Note

XmlElementAttribute appartiene a una famiglia di attributi che controlla come XmlSerializer serializza o deserializza un oggetto. Per un elenco completo di attributi analoghi, vedere Attributi che controllano la serializzazione XML.

Un documento XML generalmente contiene elementi XML, ciascuno dei quali è costituito da tre parti: un tag di apertura con gli eventuali attributi, un tag di chiusura e i dati fra i tag. I tag XML possono essere nidificati, in altre parole i dati fra i tag possono anche essere elementi XML. Questa capacità di un elemento di racchiuderne un altro consente al documento di contenere gerarchie di dati. Un elemento XML può anche includere attributi.

Applicare XmlElementAttribute ai campi pubblici o alle proprietà pubbliche in lettura/scrittura per controllare le caratteristiche degli elementi XML come il nome e lo spazio dei nomi dell'elemento.

È possibile applicare più volte XmlElementAttribute a un campo che restituisce una matrice di oggetti. Lo scopo è quello di specificare, tramite la proprietà Type, i diversi tipi che è possibile inserire nella matrice. La matrice nel codice C# riportato di seguito, ad esempio, accetta stringhe e integer.

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

L'XML risultante potrebbe essere simile al seguente.

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

Quando l'XmlElementAttribute viene applicato più volte senza specificare un valore della proprietà ElementName, gli elementi vengono denominati dopo il tipo degli oggetti accettabili.

Se si applica XmlElementAttribute a un campo o a una proprietà che restituisce una matrice, gli elementi nella matrice sono codificati come una sequenza di elementi XML.

Al contrario, se a un campo o una proprietà di questo tipo non viene applicato XmlElementAttribute, gli elementi della matrice vengono codificati come sequenza di elementi, nidificati al di sotto di un elemento denominato in base al campo o alla proprietà. Utilizzare gli attributi XmlArrayAttribute e XmlArrayItemAttribute per controllare la serializzazione di una matrice.

È possibile impostare la proprietà Type per specificare un tipo derivato dal tipo del campo o della proprietà originale, ovvero il campo o la proprietà alla quale è stato applicato l'XmlElementAttribute.

Se un campo o una proprietà restituisce un ArrayList, è possibile applicare più istanze di XmlElementAttribute al membro. Per ogni istanza, impostare la proprietà Type su un tipo di oggetto che sia possibile inserire nella matrice.

Per ulteriori informazioni sull'utilizzo degli attributi, vedere Estensione di metadati mediante attributi.

NotaNota

Nel codice è possibile utilizzare la parola XmlElement anziché la forma più estesa XmlElementAttribute.

Esempio

Nell'esempio riportato di seguito viene serializzata una classe denominata Group e applicato XmlElementAttribute a molti dei membri. Il campo denominato Employees restituisce una matrice di oggetti Employee. In questo caso, XmlElementAttribute specifica che l'XML risultante non deve essere nidificato, come da comportamento predefinito degli elementi di una matrice.

Visual Basic
Imports System
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


C#
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);
      }
   }
}
   

C++
#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" );
}

J#
import System.*;
import System.Collections.*;
import System.IO.*;
import 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. */
   
    /** @attribute XmlElement(ElementName = "Members",
        Namespace = "http://www.cpandl.com")
     */
    public Employee employees[];   
    /** @attribute XmlElement(DataType = "double", ElementName = "Building")
     */
    public double groupID;   
    /** @attribute XmlElement(DataType = "hexBinary")
     */
    public ubyte hexBytes[];   
    /** @attribute XmlElement(DataType = "boolean")
     */
    public boolean isActive;   
    /** @attribute XmlElement(Type = Manager.class)
     */
    public Employee manager;   
    /** @attribute XmlElement(int.class, ElementName = "ObjectNumber")
        @attribute XmlElement(String.class, ElementName = "ObjectString")
     */
    public ArrayList extraInfo;
} //Group

public class Employee
{
    public String name;
} //Employee

public class Manager extends Employee
{
    public int level;
} //Manager

public class Run
{
    public static void main(String[] args)
    {
        Run test = new Run();
        test.SerializeObject("FirstDoc.xml");
        test.DeserializeObject("FirstDoc.xml");
    } //main

    public void SerializeObject(String fileName)
    {
        // Create the XmlSerializer.
        XmlSerializer s = new XmlSerializer(Group.class.ToType());

        // 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 ubyte[] { Convert.ToByte(100) };

        Employee x = new Employee();
        Employee y = new Employee();

        x.name = "Jack";
        y.name = "Jill";
        group.employees = new Employee[] { 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((Int32)42);
        group.extraInfo.Add("Answer");

        // Serialize the object, and close the TextWriter.      
        s.Serialize(writer, group);
        writer.Close();
    } //SerializeObject

    public void DeserializeObject(String fileName)
    {
        FileStream fs = new FileStream(fileName, FileMode.Open);
        XmlSerializer x = new XmlSerializer(Group.class.ToType());
        Group g = (Group)x.Deserialize(fs);

        Console.WriteLine(g.manager.name);
        Console.WriteLine(g.groupID);
        Console.WriteLine(g.hexBytes.get_Item(0));
        for (int iCtr = 0; iCtr < g.employees.length; iCtr++) {
            Employee e = g.employees[iCtr];
            Console.WriteLine(e.name);
        }
    } //DeserializeObject
} //Run

Gerarchia di ereditarietà

System.Object
   System.Attribute
    System.Xml.Serialization.XmlElementAttribute
Codice thread safe

I membri statici pubblici (Shared in Visual Basic) di questo tipo sono validi per le operazioni multithreading. I membri di istanza non sono garantiti come thread safe.
Piattaforme

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile per Pocket PC, Windows Mobile per Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework non supporta tutte le versioni di ciascuna piattaforma. Per un elenco delle versioni supportate, vedere Requisiti di sistema.

Informazioni sulla versione

.NET Framework

Supportato in: 2.0 1.1 1.0

.NET Compact Framework

Supportato in: 2.0 1.0
Vedere anche