Partager via


XmlAttributes Classe

Définition

Représente une collection d’objets d’attribut qui contrôlent la façon dont le XmlSerializer sérialise et désérialise un objet.

public ref class XmlAttributes
public class XmlAttributes
type XmlAttributes = class
Public Class XmlAttributes
Héritage
XmlAttributes

Exemples

L’exemple suivant sérialise une instance d’une classe nommée Orchestra, qui contient un champ unique nommé Instruments qui retourne un tableau d’objets Instrument . Une deuxième classe nommée Brass hérite de la Instrument classe. L’exemple crée un XmlAttributes objet pour remplacer le Instrument champ, ce qui permet au champ d’accepter Brass des objets, et ajoute l’objet XmlAttributes à une instance de la XmlAttributeOverrides classe.

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)
    {
      /* Each overridden field, property, or type requires
      an XmlAttributes object. */
      XmlAttributes attrs = new XmlAttributes();

      /* Create an XmlElementAttribute to override the
      field that returns Instrument objects. The overridden field
      returns Brass objects instead. */
      XmlElementAttribute attr = new XmlElementAttribute();
      attr.ElementName = "Brass";
      attr.Type = typeof(Brass);

      // Add the element to the collection of elements.
      attrs.XmlElements.Add(attr);

      // Create the XmlAttributeOverrides object.
      XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();

      /* Add the type of the class that contains the overridden
      member and the XmlAttributes to override it with to the
      XmlAttributeOverrides object. */
      attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);

      // Create the XmlSerializer using the XmlAttributeOverrides.
      XmlSerializer s =
      new XmlSerializer(typeof(Orchestra), attrOverrides);

      // Writing the file requires a TextWriter.
      TextWriter writer = new StreamWriter(filename);

      // Create the object that will be serialized.
      Orchestra band = new Orchestra();

      // Create an object of the derived type.
      Brass i = new Brass();
      i.Name = "Trumpet";
      i.IsValved = true;
      Instrument[] myInstruments = {i};
      band.Instruments = myInstruments;

      // Serialize the object.
      s.Serialize(writer,band);
      writer.Close();
   }

   public void DeserializeObject(string filename)
   {
      XmlAttributeOverrides attrOverrides =
         new XmlAttributeOverrides();
      XmlAttributes attrs = new XmlAttributes();

      // Create an XmlElementAttribute to override the Instrument.
      XmlElementAttribute attr = new XmlElementAttribute();
      attr.ElementName = "Brass";
      attr.Type = typeof(Brass);

      // Add the element to the collection of elements.
      attrs.XmlElements.Add(attr);

      attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);

      // Create 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:");

      /* The difference between deserializing the overridden
      XML document and serializing it is this: To read the derived
      object values, you must 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);
      }
   }
}
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(ByVal filename As String)
        ' Each overridden field, property, or type requires
        ' an XmlAttributes object. 
        Dim attrs As New XmlAttributes()
        
        ' Create an XmlElementAttribute to override the
        ' field that returns Instrument objects. The overridden field
        ' returns Brass objects instead. 
        Dim attr As New XmlElementAttribute()
        attr.ElementName = "Brass"
        attr.Type = GetType(Brass)
        
        ' Add the element to the collection of elements.
        attrs.XmlElements.Add(attr)
        
        ' Create the XmlAttributeOverrides object.
        Dim attrOverrides As New XmlAttributeOverrides()
        
        ' Add the type of the class that contains the overridden
        ' member and the XmlAttributes to override it with to the
        ' XmlAttributeOverrides object. 
        attrOverrides.Add(GetType(Orchestra), "Instruments", attrs)
        
        ' Create the XmlSerializer using the XmlAttributeOverrides.
        Dim s As New XmlSerializer(GetType(Orchestra), attrOverrides)
        
        ' Writing the file requires a TextWriter.
        Dim writer As New StreamWriter(filename)
        
        ' Create the object that will be serialized.
        Dim band As New Orchestra()
        
        ' Create 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
        
        ' Serialize the object.
        s.Serialize(writer, band)
        writer.Close()
    End Sub
    
    
    Public Sub DeserializeObject(ByVal filename As String)
        Dim attrOverrides As New XmlAttributeOverrides()
        Dim attrs As New XmlAttributes()
        
        ' Create an XmlElementAttribute to override the Instrument.
        Dim attr As New XmlElementAttribute()
        attr.ElementName = "Brass"
        attr.Type = GetType(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:")
        
        ' The difference between deserializing the overridden
        ' XML document and serializing it is this: To read the derived
        ' object values, you must 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

Remarques

La création de l’élément XmlAttributes fait partie d’un processus qui remplace la méthode par défaut pour XmlSerializer sérialiser les instances de classe. Par exemple, supposons que vous souhaitez sérialiser un objet créé à partir d’une DLL qui a une source inaccessible. En utilisant , XmlAttributeOverridesvous pouvez augmenter ou contrôler la façon dont l’objet est sérialisé.

Les membres de la XmlAttributes classe correspondent directement à une famille de classes d’attributs qui contrôlent la sérialisation. Par exemple, la XmlText propriété doit être définie sur un XmlTextAttribute, ce qui vous permet de remplacer la sérialisation d’un champ ou d’une propriété en demandant à XmlSerializer sérialiser la valeur de la propriété en tant que texte XML. Pour obtenir la liste complète des attributs qui contrôlent la sérialisation, consultez le XmlSerializer.

Pour plus d’informations sur l’utilisation de la XmlAttributeOverridesXmlAttributes classe, consultez Guide pratique pour spécifier un autre nom d’élément pour un flux XML.

Constructeurs

Nom Description
XmlAttributes()

Initialise une nouvelle instance de la classe XmlAttributes.

XmlAttributes(ICustomAttributeProvider)

Initialise une nouvelle instance de la XmlAttributes classe et personnalise la façon dont la XmlSerializer sérialise et désérialise un objet.

Propriétés

Nom Description
XmlAnyAttribute

Obtient ou définit la XmlAnyAttributeAttribute valeur à remplacer.

XmlAnyElements

Obtient la collection d’objets XmlAnyElementAttribute à remplacer.

XmlArray

Obtient ou définit un objet qui spécifie comment sérialise XmlSerializer un champ public ou une propriété en lecture/écriture qui retourne un tableau.

XmlArrayItems

Obtient ou définit une collection d’objets qui spécifient la façon dont les XmlSerializer éléments sérialisent insérés dans un tableau retourné par un champ public ou une propriété en lecture/écriture.

XmlAttribute

Obtient ou définit un objet qui spécifie comment sérialise XmlSerializer un champ public ou une propriété de lecture/écriture publique en tant qu’attribut XML.

XmlChoiceIdentifier

Obtient ou définit un objet qui vous permet de faire la distinction entre un ensemble de choix.

XmlDefaultValue

Obtient ou définit la valeur par défaut d’un élément ou d’un attribut XML.

XmlElements

Obtient une collection d’objets qui spécifient comment sérialise XmlSerializer un champ public ou une propriété en lecture/écriture en tant qu’élément XML.

XmlEnum

Obtient ou définit un objet qui spécifie la façon dont le XmlSerializer membre d’énumération est sérialisé.

XmlIgnore

Obtient ou définit une valeur qui spécifie si le XmlSerializer champ public ou la propriété en lecture/écriture publique est sérialisé ou non.

Xmlns

Obtient ou définit une valeur qui spécifie s’il faut conserver toutes les déclarations d’espace de noms lorsqu’un objet contenant un membre qui retourne un XmlSerializerNamespaces objet est substitué.

XmlRoot

Obtient ou définit un objet qui spécifie comment la XmlSerializer sérialise une classe en tant qu’élément racine XML.

XmlText

Obtient ou définit un objet qui indique à XmlSerializer sérialiser un champ public ou une propriété de lecture/écriture publique en tant que texte XML.

XmlType

Obtient ou définit un objet qui spécifie la façon dont la XmlSerializer sérialise une classe à laquelle l’application XmlTypeAttribute a été effectuée.

Méthodes

Nom Description
Equals(Object)

Détermine si l’objet spécifié est égal à l’objet actuel.

(Hérité de Object)
GetHashCode()

Sert de fonction de hachage par défaut.

(Hérité de Object)
GetType()

Obtient la Type de l’instance actuelle.

(Hérité de Object)
MemberwiseClone()

Crée une copie superficielle du Objectactuel.

(Hérité de Object)
ToString()

Retourne une chaîne qui représente l’objet actuel.

(Hérité de Object)

S’applique à

Voir aussi