XmlAttributeOverrides Classe
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Consente di eseguire l'override degli attributi di proprietà, campo e classe quando si utilizza XmlSerializer per serializzare o deserializzare un oggetto.
public ref class XmlAttributeOverrides
public class XmlAttributeOverrides
type XmlAttributeOverrides = class
Public Class XmlAttributeOverrides
- Ereditarietà
-
XmlAttributeOverrides
Esempio
Nell'esempio seguente viene serializzata una classe denominata Orchestra, che contiene un singolo campo denominato Instruments che restituisce una matrice di Instrument oggetti. Una seconda classe denominata Brass eredita dalla Instrument classe . Nell'esempio viene utilizzata un'istanza della XmlAttributeOverrides classe per eseguire l'override del Instrument campo, consentendo al campo di accettare Brass oggetti.
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
Commenti
XmlAttributeOverrides consente a di eseguire l'override XmlSerializer del modo predefinito di serializzare un set di oggetti. L'override della serializzazione in questo modo prevede due usi: per prima cosa, è possibile controllare e aumentare la serializzazione degli oggetti trovati in una DLL, anche se non si ha accesso all'origine; in secondo luogo, è possibile creare un set di classi serializzabili, ma serializzare gli oggetti in più modi. Ad esempio, anziché serializzare i membri di un'istanza di classe come elementi XML, è possibile serializzarli come attributi XML, ottenendo un documento più efficiente da trasportare.
Dopo aver creato un XmlAttributeOverrides oggetto, passarlo come argomento al XmlSerializer costruttore. L'oggetto risultante XmlSerializer usa i dati contenuti da per eseguire l'override XmlAttributeOverrides degli attributi che controllano la modalità di serializzazione degli oggetti. A tale scopo, XmlAttributeOverrides contiene una raccolta dei tipi di oggetto di cui viene eseguito l'override, nonché un XmlAttributes oggetto associato a ogni tipo di oggetto sottoposto a override. L'oggetto XmlAttributes stesso contiene un set appropriato di oggetti attributo che controllano la modalità di serializzazione di ogni campo, proprietà o classe.
Il processo per la creazione e l'uso di un XmlAttributeOverrides oggetto è il seguente:
Creare un oggetto XmlAttributes.
Creare un oggetto attributo appropriato per l'oggetto sottoposto a override. Ad esempio, per eseguire l'override di un campo o di una proprietà, creare un XmlElementAttributeoggetto usando il nuovo tipo derivato. Facoltativamente, è possibile assegnare un nuovo ElementNameoggetto o Namespace che esegue l'override del nome o dello spazio dei nomi dell'attributo della classe di base.
Aggiungere l'oggetto attributo alla proprietà o alla raccolta appropriata XmlAttributes . Ad esempio, aggiungere l'oggetto XmlElementAttribute all'insieme XmlElements dell'oggetto XmlAttributes , specificando il nome del membro sottoposto a override.
Creare un oggetto XmlAttributeOverrides.
Usando il Add metodo , aggiungere l'oggetto XmlAttributes all'oggetto XmlAttributeOverrides . Se l'oggetto sottoposto a override è o XmlRootAttributeXmlTypeAttribute, è necessario specificare solo il tipo dell'oggetto sottoposto a override. Tuttavia, se si esegue l'override di un campo o di una proprietà, è necessario specificare anche il nome del membro sottoposto a override.
Quando si costruisce , XmlSerializerpassare all'oggetto XmlAttributeOverrides al XmlSerializer costruttore .
Utilizzare l'oggetto risultante XmlSerializer per serializzare o deserializzare gli oggetti classe derivata.
Costruttori
| Nome | Descrizione |
|---|---|
| XmlAttributeOverrides() |
Inizializza una nuova istanza della classe XmlAttributeOverrides. |
Proprietà
| Nome | Descrizione |
|---|---|
| Item[Type, String] |
Ottiene l'oggetto associato al tipo specificato (classe base). Il parametro membro specifica il membro della classe base sottoposto a override. |
| Item[Type] |
Ottiene l'oggetto associato al tipo specificato, classe base. |
Metodi
| Nome | Descrizione |
|---|---|
| Add(Type, String, XmlAttributes) |
Aggiunge un XmlAttributes oggetto all'insieme di XmlAttributes oggetti . Il |
| Add(Type, XmlAttributes) |
Aggiunge un XmlAttributes oggetto all'insieme di XmlAttributes oggetti . Il |
| Equals(Object) |
Determina se l'oggetto specificato è uguale all'oggetto corrente. (Ereditato da Object) |
| GetHashCode() |
Funge da funzione hash predefinita. (Ereditato da Object) |
| GetType() |
Ottiene il Type dell'istanza corrente. (Ereditato da Object) |
| MemberwiseClone() |
Crea una copia superficiale del Objectcorrente. (Ereditato da Object) |
| ToString() |
Restituisce una stringa che rappresenta l'oggetto corrente. (Ereditato da Object) |
Si applica a
Vedi anche
- Deserialize(Stream)
- Serialize(TextWriter, Object)
- XmlSerializer
- XmlAttributes
- Introduzione alla serializzazione XML
- Procedura: Specificare un nome di elemento alternativo per un flusso XML
- Controllo della serializzazione XML tramite attributi
- Esempi di serializzazione XML
- Xml Schema Definition Tool (Xsd.exe)