XmlAttributeOverrides Classe
Définition
Important
Certaines informations portent sur la préversion du produit qui est susceptible d’être en grande partie modifiée avant sa publication. Microsoft exclut toute garantie, expresse ou implicite, concernant les informations fournies ici.
Vous permet de remplacer les attributs de propriété, de champ et de classe lorsque vous utilisez la XmlSerializer propriété pour sérialiser ou désérialiser un objet.
public ref class XmlAttributeOverrides
public class XmlAttributeOverrides
type XmlAttributeOverrides = class
Public Class XmlAttributeOverrides
- Héritage
-
XmlAttributeOverrides
Exemples
L’exemple suivant sérialise 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 utilise une instance de la XmlAttributeOverrides classe pour remplacer le Instrument champ, ce qui permet au champ d’accepter des Brass objets.
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 XmlElementAttribute to the collection of objects.
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);
}
}
}
Option Explicit
Option Strict
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(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 XmlElementAttribute to the collection of objects.
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)
Next i
End Sub
End Class
Remarques
Permet XmlAttributeOverridesXmlSerializer de remplacer la méthode par défaut de sérialisation d’un ensemble d’objets. La substitution de la sérialisation de cette façon a deux utilisations : tout d’abord, vous pouvez contrôler et augmenter la sérialisation des objets trouvés dans une DLL, même si vous n’avez pas accès à la source ; deuxièmement, vous pouvez créer un ensemble de classes sérialisables, mais sérialiser les objets de plusieurs façons. Par exemple, au lieu de sérialiser des membres d’une instance de classe en tant qu’éléments XML, vous pouvez les sérialiser en tant qu’attributs XML, ce qui entraîne un transport d’un document plus efficace.
Après avoir créé un XmlAttributeOverrides objet, vous le transmettez en tant qu’argument au XmlSerializer constructeur. Les résultats XmlSerializer utilisent les données contenues par les XmlAttributeOverrides attributs pour remplacer les attributs qui contrôlent la façon dont les objets sont sérialisés. Pour ce faire, il XmlAttributeOverrides contient une collection des types d’objets qui sont substitués, ainsi qu’un objet associé à chaque type d’objet XmlAttributes substitué. L’objet XmlAttributes lui-même contient un ensemble approprié d’objets d’attribut qui contrôlent la façon dont chaque champ, propriété ou classe est sérialisé.
Le processus de création et d’utilisation d’un XmlAttributeOverrides objet est le suivant :
Créez un objet XmlAttributes.
Créez un objet d’attribut approprié à l’objet en cours de substitution. Par exemple, pour remplacer un champ ou une propriété, créez un XmlElementAttribute, à l’aide du nouveau type dérivé. Vous pouvez éventuellement affecter un nouveau ElementNameou Namespace qui remplace le nom ou l’espace de noms de l’attribut de la classe de base.
Ajoutez l’objet d’attribut à la propriété ou à la collection appropriée XmlAttributes . Par exemple, vous devez ajouter la XmlElementAttributeXmlElements collection de l’objet XmlAttributes , en spécifiant le nom de membre en cours de substitution.
Créez un objet XmlAttributeOverrides.
À l’aide de la Add méthode, ajoutez l’objet XmlAttributes à l’objet XmlAttributeOverrides . Si l’objet en cours de substitution est un XmlRootAttribute ou XmlTypeAttribute, vous devez uniquement spécifier le type de l’objet substitué. Toutefois, si vous remplacez un champ ou une propriété, vous devez également spécifier le nom du membre substitué.
Lors de la construction du XmlSerializer, passez le XmlAttributeOverrides constructeur XmlSerializer .
Utilisez le résultat XmlSerializer pour sérialiser ou désérialiser les objets de classe dérivés.
Constructeurs
| Nom | Description |
|---|---|
| XmlAttributeOverrides() |
Initialise une nouvelle instance de la classe XmlAttributeOverrides. |
Propriétés
| Nom | Description |
|---|---|
| Item[Type, String] |
Obtient l’objet associé au type spécifié (classe de base). Le paramètre membre spécifie le membre de classe de base qui est substitué. |
| Item[Type] |
Obtient l’objet associé au type de classe de base spécifié. |
Méthodes
| Nom | Description |
|---|---|
| Add(Type, String, XmlAttributes) |
Ajoute un XmlAttributes objet à la collection d’objets XmlAttributes . Le |
| Add(Type, XmlAttributes) |
Ajoute un XmlAttributes objet à la collection d’objets XmlAttributes . Le |
| 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
- Deserialize(Stream)
- Serialize(TextWriter, Object)
- XmlSerializer
- XmlAttributes
- Présentation de la sérialisation XML
- Guide pratique pour spécifier un autre nom d’élément pour un flux XML
- Contrôle de la sérialisation XML à l’aide d’attributs
- Exemples de sérialisation XML
- Outil de définition de schéma XML (Xsd.exe)