Serializza e deserializza oggetti in e da documenti XML. XmlSerializer consente di controllare le modalità di codifica degli oggetti in XML.
System.Xml.Serialization.XmlSerializer
Spazio dei nomi: System.Xml.Serialization
Assembly: System.Xml (in System.Xml.dll)
Public Class XmlSerializer
public class XmlSerializer
public ref class XmlSerializer
type XmlSerializer = class end
Il tipo XmlSerializer espone i seguenti membri.
| Nome | Descrizione | |
|---|---|---|
|
XmlSerializer() | Infrastruttura. Inizializza una nuova istanza della classe XmlSerializer. |
|
XmlSerializer(Type) | Inizializza una nuova istanza della classe XmlSerializer in grado di serializzare gli oggetti del tipo specificato in documenti XML e di deserializzare documenti XML in oggetti del tipo specificato. |
|
XmlSerializer(XmlTypeMapping) | Inizializza un'istanza della classe XmlSerializer tramite un oggetto che esegue il mapping di un tipo a un altro. |
|
XmlSerializer(Type, String) | Inizializza una nuova istanza della classe XmlSerializer in grado di serializzare gli oggetti del tipo specificato in documenti XML e di deserializzare documenti XML in oggetti del tipo specificato. Specifica lo spazio dei nomi predefinito per tutti gli elementi XML. |
|
XmlSerializer(Type, Type[]) | Inizializza una nuova istanza della classe XmlSerializer in grado di serializzare gli oggetti del tipo specificato in documenti XML e di deserializzare documenti XML in oggetti di un tipo specificato. Se una proprietà o un campo restituisce una matrice, il parametro extraTypes specifica gli oggetti che possono essere inseriti nella matrice. |
|
XmlSerializer(Type, XmlAttributeOverrides) | Inizializza una nuova istanza della classe XmlSerializer in grado di serializzare gli oggetti del tipo specificato in documenti XML e di deserializzare documenti XML in oggetti del tipo specificato. Ciascun oggetto da serializzare può contenere istanze di classi e questo overload può eseguire l'override con altre classi. |
|
XmlSerializer(Type, XmlRootAttribute) | Inizializza una nuova istanza della classe XmlSerializer in grado di serializzare gli oggetti del tipo specificato in documenti XML e di deserializzare documenti XML in oggetti del tipo specificato. Specifica inoltre la classe da utilizzare come elemento XML di primo livello. |
|
XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String) | Inizializza una nuova istanza della classe XmlSerializer in grado di serializzare oggetti di tipo Object in istanze di documento XML e di deserializzare istanze di documento XML in oggetti di tipo Object. Ciascun oggetto da serializzare può contenere istanze di classi e questo overload ne esegue l'override con altre classi. Questo overload specifica inoltre lo spazio dei nomi predefinito per tutti gli elementi XML e la classe da utilizzare come elemento XML di primo livello. |
|
XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String) | Inizializza una nuova istanza della classe XmlSerializer in grado di serializzare oggetti di tipo Object in istanze di documento XML e di deserializzare istanze di documento XML in oggetti di tipo Object. Ciascun oggetto da serializzare può contenere istanze di classi e questo overload ne esegue l'override con altre classi. Questo overload specifica inoltre lo spazio dei nomi predefinito per tutti gli elementi XML e la classe da utilizzare come elemento XML di primo livello. |
|
XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String, Evidence) | Infrastruttura. Obsoleta. Inizializza una nuova istanza della classe XmlSerializer in grado di serializzare gli oggetti del tipo specificato in istanze di documento XML e di deserializzare istanze di documento XML in oggetti del tipo specificato. Questo overload consente di fornire altri tipi rilevabili durante un'operazione di serializzazione o deserializzazione, nonché uno spazio dei nomi predefinito per tutti gli elementi XML, la classe da utilizzare come elemento XML di primo livello, la relativa posizione e le credenziali necessarie per l'accesso. |
| Nome | Descrizione | |
|---|---|---|
|
CanDeserialize | Ottiene un valore che indica se questo XmlSerializer può deserializzare un documento XML specificato. |
|
CreateReader | Infrastruttura. Restituisce un oggetto utilizzato per leggere il documento XML da serializzare. |
|
CreateWriter | Infrastruttura. Quando sottoposto a override in una classe derivata, restituisce un writer utilizzato per serializzare l'oggetto. |
|
Deserialize(Stream) | Deserializza il documento XML contenuto dal Stream specificato. |
|
Deserialize(TextReader) | Deserializza il documento XML contenuto dal TextReader specificato. |
|
Deserialize(XmlReader) | Deserializza il documento XML contenuto dal XmlReader specificato. |
|
Deserialize(XmlSerializationReader) | Infrastruttura. Deserializza il documento XML contenuto dalla classe XmlSerializationReader specificata. |
|
Deserialize(XmlReader, String) | Deserializza il documento XML contenuto nel XmlReader specificato e lo stile di codifica. |
|
Deserialize(XmlReader, XmlDeserializationEvents) | Deserializza un documento XML contenuto nell'oggetto XmlReader specificato e consente l'override degli eventi che si verificano durante la deserializzazione. |
|
Deserialize(XmlReader, String, XmlDeserializationEvents) | Infrastruttura. Deserializza l'oggetto utilizzando i dati contenuti nell'oggetto XmlReader specificato. |
|
Equals(Object) | Determina se l'oggetto Object specificato è uguale all'oggetto Object corrente. (Ereditato da Object) |
|
Finalize | Consente a un oggetto di provare a liberare risorse ed eseguire altre operazioni di pulitura prima che l'oggetto stesso venga recuperato dalla procedura di Garbage Collection. (Ereditato da Object) |
|
FromMappings(XmlMapping[]) | Infrastruttura. Restituisce una matrice di oggetti XmlSerializer creati da una matrice di oggetti XmlTypeMapping. |
|
FromMappings(XmlMapping[], Evidence) | Obsoleta. Restituisce un'istanza della classe XmlSerializer creata dai mapping di un tipo XML a un altro. |
|
FromMappings(XmlMapping[], Type) | Infrastruttura. Restituisce un'istanza della classe XmlSerializer dai mapping specificati. |
|
FromTypes | Restituisce una matrice di oggetti XmlSerializer creati da una matrice di tipi. |
|
GenerateSerializer(Type[], XmlMapping[]) | Infrastruttura. Restituisce un assembly contenente serializzatori personalizzati utilizzati per serializzare o deserializzare i tipi specificati, mediante i mapping specificati. |
|
GenerateSerializer(Type[], XmlMapping[], CompilerParameters) | Infrastruttura. Restituisce un assembly contenente serializzatori personalizzati utilizzati per serializzare o deserializzare i tipi specificati, mediante le impostazioni e opzioni del compilatore e i mapping specificati. |
|
GetHashCode | Funge da funzione hash per un determinato tipo. (Ereditato da Object) |
|
GetType | Ottiene l'oggetto Type dell'istanza corrente. (Ereditato da Object) |
|
GetXmlSerializerAssemblyName(Type) | Restituisce il nome dell'assembly contenente una o più versioni di XmlSerializer appositamente create per serializzare o deserializzare il tipo specificato. |
|
GetXmlSerializerAssemblyName(Type, String) | Restituisce il nome dell'assembly contenente il serializzatore per il tipo specificato nello spazio dei nomi specificato. |
|
MemberwiseClone | Consente di creare una copia dei riferimenti dell'oggetto Object corrente. (Ereditato da Object) |
|
Serialize(Object, XmlSerializationWriter) | Infrastruttura. Serializza la classe Object specificata e scrive il documento XML in un file utilizzando la classe XmlSerializationWriter specificata. |
|
Serialize(Stream, Object) | Serializza l'Object specificato e scrive il documento XML in un file utilizzando il Stream specificato. |
|
Serialize(TextWriter, Object) | Serializza l'Object specificato e scrive il documento XML in un file utilizzando il TextWriter specificato. |
|
Serialize(XmlWriter, Object) | Serializza l'Object specificato e scrive il documento XML in un file utilizzando il XmlWriter specificato. |
|
Serialize(Stream, Object, XmlSerializerNamespaces) | Serializza l'oggetto Object specificato e scrive il documento XML in un file mediante l'oggetto Stream specificato, che fa riferimento agli spazi dei nomi specificati. |
|
Serialize(TextWriter, Object, XmlSerializerNamespaces) | Serializza l'oggetto Object specificato e scrive il documento XML in un file mediante l'oggetto TextWriter specificato, facendo riferimento agli spazi dei nomi specificati. |
|
Serialize(XmlWriter, Object, XmlSerializerNamespaces) | Serializza l'oggetto Object specificato e scrive il documento XML in un file mediante l'oggetto XmlWriter specificato, facendo riferimento agli spazi dei nomi specificati. |
|
Serialize(XmlWriter, Object, XmlSerializerNamespaces, String) | Serializza l'oggetto specificato e scrive il documento XML in un file mediante l'oggetto XmlWriter specificato, facendo riferimento agli spazi dei nomi specificati. |
|
Serialize(XmlWriter, Object, XmlSerializerNamespaces, String, String) | Serializza l'oggetto Object specificato e scrive il documento XML in un file mediante l'oggetto XmlWriter, gli spazi dei nomi XML e la codifica specificati. |
|
ToString | Restituisce una stringa che rappresenta l'oggetto corrente. (Ereditato da Object) |
| Nome | Descrizione | |
|---|---|---|
|
UnknownAttribute | Si verifica quando XmlSerializer incontra un attributo XML di tipo sconosciuto durante la deserializzazione. |
|
UnknownElement | Si verifica quando XmlSerializer incontra un elemento XML di tipo sconosciuto durante la deserializzazione. |
|
UnknownNode | Si verifica quando XmlSerializer incontra un nodo XML di tipo sconosciuto durante la deserializzazione. |
|
UnreferencedObject | Si verifica durante la deserializzazione di un flusso XML con codifica SOAP, quando XmlSerializer rileva un tipo riconosciuto che non viene utilizzato o a cui non viene fatto riferimento. |
La serializzazione XML è il processo di conversione delle proprietà e dei campi pubblici di un oggetto in un formato seriale (in questo caso, XML) per la memorizzazione o il trasferimento. La deserializzazione ricrea l'oggetto nel suo stato originale dall'output XML. È possibile pensare alla serializzazione come a una modalità di salvataggio dello stato di un oggetto in un flusso o in un buffer. Ad esempio, ASP.NET utilizza la classe XmlSerializer per codificare i messaggi del servizio Web XML.
I dati negli oggetti sono descritti tramite costrutti del linguaggio di programmazione come classi, campi, proprietà, tipi primitivi, matrici e anche XML incorporati sotto forma di oggetti XmlElement o XmlAttribute. È possibile creare le classi, annotate con attributi, o utilizzare XML Schema Definition Tool (Xsd.exe) per generare le classi basate su un documento XSD (XML Schema Definition) esistente. Se si dispone di uno schema XML, è possibile eseguire il programma Xsd.exe per generare un insieme di classi fortemente tipizzate rispetto allo schema e annotate con attributi per aderire allo schema quando sono serializzate.
Il trasferimento di dati tra oggetti e XML richiede un mapping dai costrutti del linguaggio di programmazione allo schema XML e viceversa. XmlSerializer e gli strumenti correlati come Xsd.exe fungono da ponte tra queste due tecnologie in fase di progettazione e di esecuzione. In fase di progettazione, utilizzare Xsd.exe per generare un documento di schema XML (xsd) dalle classi personalizzate oppure per generare classi da un determinato schema. In entrambi i casi le classi vengono annotate con attributi personalizzati in modo da consentire il mapping da parte di XmlSerializer tra il sistema di schema XML e il Common Language Runtime (CLR). In fase di esecuzione, le istanze delle classi possono essere serializzate in documenti XML che adottano lo schema. Analogamente, è possibile deserializzare questi documenti XML in oggetti in fase di esecuzione. Lo schema XML è facoltativo e non è necessario in fase di progettazione o di esecuzione.
Controllo di XML generato
Per controllare l'XML generato, è possibile applicare speciali attributi alle classi e ai membri. Per specificare, ad esempio, un nome di elemento XML diverso, applicare un XmlElementAttribute a una proprietà o a un campo pubblico e impostare la proprietà ElementName. Per un elenco completo di attributi analoghi, vedere Attributes That Control XML Serialization. Per controllare l'output XML è anche possibile implementare l'interfaccia IXmlSerializable.
Se è necessario che l'XML generato sia conforme alla sezione 5 del documento "Simple Object Access Protocol (SOAP) 1.1" del World Wide Web Consortium (www.w3.org), è necessario creare l'XmlSerializer con un XmlTypeMapping. Per controllare ulteriormente l'XML SOAP codificato, utilizzare gli attributi elencati in Attributes That Control Encoded SOAP Serialization.
Con XmlSerializer si può sfruttare la possibilità di lavorare con classi fortemente tipizzate pur mantenendo la flessibilità di XML. Utilizzando i campi e le proprietà di tipo XmlElement, XmlAttribute o XmlNode nelle classi fortemente tipizzate, è possibile leggere parti del documento XML direttamente negli oggetti XML.
Se si utilizzano schemi XML estensibili, è anche possibile utilizzare gli attributi XmlAnyElementAttribute e XmlAnyAttributeAttribute per serializzare e deserializzare gli elementi o gli attributi non trovati nello schema originale. Per utilizzare gli oggetti, applicare un XmlAnyElementAttribute a un campo che restituisce una matrice di oggetti XmlElement o applicare un XmlAnyAttributeAttribute a un campo che restituisce una matrice di oggetti XmlAttribute.
Se una proprietà o un campo restituisce un oggetto complesso (come una matrice o l'istanza di una classe), XmlSerializer lo converte in un elemento annidato nel documento XML principale. Ad esempio, la prima classe nel seguente codice restituisce un'istanza della seconda classe.
Public Class MyClass Public MyObjectProperty As MyObject End Class Public Class MyObject Public ObjectName As String End Class
public class MyClass { public MyObject MyObjectProperty; } public class MyObject { public string ObjectName; }
L'output XML serializzato ha questo aspetto:
<MyClass> <MyObjectProperty> <ObjectName>My String</ObjectName> </MyObjectProperty> </MyClass>
Se uno schema include un elemento facoltativo (minOccurs = '0') oppure un valore predefinito, sono disponibili due scelte. La prima consiste nell'utilizzare System.ComponentModel.DefaultValueAttribute per specificare il valore predefinito, come illustrato nel codice riportato di seguito.
Public Class PurchaseOrder <System.ComponentModel.DefaultValueAttribute ("2002")> _ Public Year As String End Class
public class PurchaseOrder { [System.ComponentModel.DefaultValueAttribute ("2002")] public string Year; }
Un'ulteriore scelta consiste nell'utilizzo di un criterio speciale per creare un campo booleano riconosciuto da XmlSerializer e applicare l'oggetto XmlIgnoreAttribute al campo. Il criterio viene creato nel formato propertyNameSpecified. Se, ad esempio, è presente un campo denominato "MyFirstName", si creerà anche un campo denominato "MyFirstNameSpecified" per indicare a XmlSerializer l'eventuale necessità di generare l'elemento XML denominato "MyFirstName", come illustrato nell'esempio riportato di seguito.
Public Class OptionalOrder ' This field's value should not be serialized ' if it is uninitialized. Public FirstOrder As String ' Use the XmlIgnoreAttribute to ignore the ' special field named "FirstOrderSpecified". <System.Xml.Serialization.XmlIgnoreAttribute> _ Public FirstOrderSpecified As Boolean End Class
public class OptionalOrder { // This field should not be serialized // if it is uninitialized. public string FirstOrder; // Use the XmlIgnoreAttribute to ignore the // special field named "FirstOrderSpecified". [System.Xml.Serialization.XmlIgnoreAttribute] public bool FirstOrderSpecified; }
Override della serializzazione predefinita
È anche possibile eseguire l'override della serializzazione di un insieme di oggetti e dei relativi campi e proprietà creando uno degli attributi necessari e aggiungendolo a un'istanza della classe XmlAttributes. Questo tipo di override della serializzazione ha due utilizzi. In primo luogo, è possibile controllare e ottimizzare la serializzazione degli oggetti presenti in una DLL, anche se non si ha accesso all'origine. In secondo luogo, è possibile creare un insieme di classi serializzabili, serializzando tuttavia gli oggetti in più modi. Per ulteriori dettagli, vedere la classe XmlAttributeOverrides e How to: Control Serialization of Derived Classes.
Per serializzare un oggetto, chiamare il metodo Serialize. Per deserializzare un oggetto, chiamare il metodo Deserialize.
Per aggiungere spazi dei nomi XML a un documento XML, vedere XmlSerializerNamespaces.
Nota
|
|---|
|
XmlSerializer esegue un trattamento speciale per le classi che implementano IEnumerable o ICollection. Una classe che implementa IEnumerable deve implementare un metodo Add pubblico che accetta un solo parametro. Il parametro del metodo Add deve essere dello stesso tipo di quello restituito dalla proprietà Current sul valore restituito da GetEnumerator o una delle basi di tale tipo. Una classe che implementa ICollection (come CollectionBase) oltre a IEnumerable deve avere una proprietà indicizzata Item pubblica (indexer in C#) che accetta un intero e deve disporre di una proprietà Count pubblica di tipo Integer. Il parametro passato al metodo Add deve essere dello stesso tipo di quello restituito dalla proprietà Item o una delle basi di tale tipo. Per le classi che implementano ICollection, i valori da serializzare vengono recuperati dalla proprietà Item indicizzata e non chiamando GetEnumerator. |
Per deserializzare un oggetto è necessario disporre dell'autorizzazione di scrittura nella directory temporanea, in base alla definizione della variabile di ambiente TEMP.
Assembly generati in modo dinamico
Per migliorare le prestazioni, l'infrastruttura di serializzazione XML genera assembly in modo dinamico per serializzare e deserializzare tipi specifici. Tali assembly vengono recuperati e riutilizzati dall'infrastruttura. Questo comportamento si verifica solo in caso di utilizzo dei seguenti costruttori:
XmlSerializer.XmlSerializer(Type)
XmlSerializer.XmlSerializer(Type, String)
Se si utilizza un altro costruttore, vengono generate più versioni dello stesso assembly che non vengono mai scaricate, con la conseguenza di determinare una perdita di memoria e un calo di prestazioni. La soluzione più semplice consiste nell'utilizzare uno dei due costruttori indicati prima. In caso contrario, è necessario memorizzare nella cache gli assembly in un Hashtable, come illustrato nell'esempio riportato di seguito.
Hashtable serializers = new Hashtable(); // Use the constructor that takes a type and XmlRootAttribute. XmlSerializer s = new XmlSerializer(typeof(MyClass), myRoot); // Implement a method named GenerateKey that creates unique keys // for each instance of the XmlSerializer. The code should take // into account all parameters passed to the XmlSerializer // constructor. object key = GenerateKey(typeof(MyClass), myRoot); // Check the local cache for a matching serializer. XmlSerializer ser = (XmlSerializer)serializers[key]; if (ser == null) { ser = new XmlSerializer(typeof(MyClass), myRoot); // Cache the serializer. serializers[key] = ser; } else { // Use the serializer to serialize, or deserialize. }
Dim serializers As New Hashtable() ' Use the constructor that takes a type and XmlRootAttribute. Dim s As New XmlSerializer(GetType([MyClass]), myRoot) ' Implement a method named GenerateKey that creates unique keys ' for each instance of the XmlSerializer. The code should take ' into account all parameters passed to the XmlSerializer ' constructor. Dim key As Object = GenerateKey(GetType([MyClass]), myRoot) ' Check the local cache for a matching serializer. Dim ser As XmlSerializer = CType(serializers(key), XmlSerializer) If ser Is Nothing Then ser = New XmlSerializer(GetType([MyClass]), myRoot) ' Cache the serializer. serializers(key) = ser Else ' Use the serializer to serialize, or deserialize. End If
Serializzazione di ArrayList e di elenchi generici
La classe XmlSerializer non è in grado di serializzare o deserializzare i seguenti elementi:
Serializzazione di enumerazioni di tipo long senza segno
Non è possibile creare istanze di XmlSerializer per serializzare un'enumerazione se si verificano le condizioni seguenti: l'enumerazione è di tipo long senza segno (ulong in C#) e contiene un qualsiasi membro con valore maggiore di 9.223.372.036.854.775.807. Quanto segue, ad esempio, non può essere serializzato.
public enum LargeNumbers: ulong
{
a = 9223372036854775808
}
// At runtime, the following code will fail.
xmlSerializer mySerializer=new XmlSerializer(typeof(LargeNumbers));
Gli oggetti contrassegnati con l'attributo Obsolete non vengono più serializzati
In la classe XmlSerializer non serializza più gli oggetti contrassegnati come [Obsolete].
Nell'esempio riportato di seguito sono contenute due classi principali: PurchaseOrder e Test. La classe PurchaseOrder contiene informazioni su un singolo acquisto. La classe Test contiene i metodi per la creazione dell'ordine di acquisto e la lettura dell'ordine creato.
Imports System Imports System.Xml Imports System.Xml.Serialization Imports System.IO Imports Microsoft.VisualBasic ' The XmlRootAttribute allows you to set an alternate name ' (PurchaseOrder) of the XML element, the element namespace; by ' default, the XmlSerializer uses the class name. The attribute ' also allows you to set the XML namespace for the element. Lastly, ' the attribute sets the IsNullable property, which specifies whether ' the xsi:null attribute appears if the class instance is set to ' a null reference. <XmlRootAttribute("PurchaseOrder", _ Namespace := "http://www.cpandl.com", IsNullable := False)> _ Public Class PurchaseOrder Public ShipTo As Address Public OrderDate As String ' The XmlArrayAttribute changes the XML element name ' from the default of "OrderedItems" to "Items". <XmlArrayAttribute("Items")> _ Public OrderedItems() As OrderedItem Public SubTotal As Decimal Public ShipCost As Decimal Public TotalCost As Decimal End Class 'PurchaseOrder Public Class Address ' The XmlAttribute instructs the XmlSerializer to serialize the Name ' field as an XML attribute instead of an XML element (the default ' behavior). <XmlAttribute()> _ Public Name As String Public Line1 As String ' Setting the IsNullable property to false instructs the ' XmlSerializer that the XML attribute will not appear if ' the City field is set to a null reference. <XmlElementAttribute(IsNullable := False)> _ Public City As String Public State As String Public Zip As String End Class 'Address Public Class OrderedItem Public ItemName As String Public Description As String Public UnitPrice As Decimal Public Quantity As Integer Public LineTotal As Decimal ' Calculate is a custom method that calculates the price per item, ' and stores the value in a field. Public Sub Calculate() LineTotal = UnitPrice * Quantity End Sub 'Calculate End Class 'OrderedItem Public Class Test Public Shared Sub Main() ' Read and write purchase orders. Dim t As New Test() t.CreatePO("po.xml") t.ReadPO("po.xml") End Sub 'Main Private Sub CreatePO(filename As String) ' Create an instance of the XmlSerializer class; ' specify the type of object to serialize. Dim serializer As New XmlSerializer(GetType(PurchaseOrder)) Dim writer As New StreamWriter(filename) Dim po As New PurchaseOrder() ' Create an address to ship and bill to. Dim billAddress As New Address() billAddress.Name = "Teresa Atkinson" billAddress.Line1 = "1 Main St." billAddress.City = "AnyTown" billAddress.State = "WA" billAddress.Zip = "00000" ' Set ShipTo and BillTo to the same addressee. po.ShipTo = billAddress po.OrderDate = System.DateTime.Now.ToLongDateString() ' Create an OrderedItem object. Dim i1 As New OrderedItem() i1.ItemName = "Widget S" i1.Description = "Small widget" i1.UnitPrice = CDec(5.23) i1.Quantity = 3 i1.Calculate() ' Insert the item into the array. Dim items(0) As OrderedItem items(0) = i1 po.OrderedItems = items ' Calculate the total cost. Dim subTotal As New Decimal() Dim oi As OrderedItem For Each oi In items subTotal += oi.LineTotal Next oi po.SubTotal = subTotal po.ShipCost = CDec(12.51) po.TotalCost = po.SubTotal + po.ShipCost ' Serialize the purchase order, and close the TextWriter. serializer.Serialize(writer, po) writer.Close() End Sub 'CreatePO Protected Sub ReadPO(filename As String) ' Create an instance of the XmlSerializer class; ' specify the type of object to be deserialized. Dim serializer As New XmlSerializer(GetType(PurchaseOrder)) ' If the XML document has been altered with unknown ' nodes or attributes, handle them with the ' UnknownNode and UnknownAttribute events. AddHandler serializer.UnknownNode, AddressOf serializer_UnknownNode AddHandler serializer.UnknownAttribute, AddressOf serializer_UnknownAttribute ' A FileStream is needed to read the XML document. Dim fs As New FileStream(filename, FileMode.Open) ' Declare an object variable of the type to be deserialized. Dim po As PurchaseOrder ' Use the Deserialize method to restore the object's state with ' data from the XML document. po = CType(serializer.Deserialize(fs), PurchaseOrder) ' Read the order date. Console.WriteLine(("OrderDate: " & po.OrderDate)) ' Read the shipping address. Dim shipTo As Address = po.ShipTo ReadAddress(shipTo, "Ship To:") ' Read the list of ordered items. Dim items As OrderedItem() = po.OrderedItems Console.WriteLine("Items to be shipped:") Dim oi As OrderedItem For Each oi In items Console.WriteLine((ControlChars.Tab & oi.ItemName & ControlChars.Tab & _ oi.Description & ControlChars.Tab & oi.UnitPrice & ControlChars.Tab & _ oi.Quantity & ControlChars.Tab & oi.LineTotal)) Next oi ' Read the subtotal, shipping cost, and total cost. Console.WriteLine(( New String(ControlChars.Tab, 5) & _ " Subtotal" & ControlChars.Tab & po.SubTotal)) Console.WriteLine(New String(ControlChars.Tab, 5) & _ " Shipping" & ControlChars.Tab & po.ShipCost ) Console.WriteLine( New String(ControlChars.Tab, 5) & _ " Total" & New String(ControlChars.Tab, 2) & po.TotalCost) End Sub 'ReadPO Protected Sub ReadAddress(a As Address, label As String) ' Read the fields of the Address object. Console.WriteLine(label) Console.WriteLine(ControlChars.Tab & a.Name) Console.WriteLine(ControlChars.Tab & a.Line1) Console.WriteLine(ControlChars.Tab & a.City) Console.WriteLine(ControlChars.Tab & a.State) Console.WriteLine(ControlChars.Tab & a.Zip) Console.WriteLine() End Sub 'ReadAddress Private Sub serializer_UnknownNode(sender As Object, e As XmlNodeEventArgs) Console.WriteLine(("Unknown Node:" & e.Name & ControlChars.Tab & e.Text)) End Sub 'serializer_UnknownNode Private Sub serializer_UnknownAttribute(sender As Object, e As XmlAttributeEventArgs) Dim attr As System.Xml.XmlAttribute = e.Attr Console.WriteLine(("Unknown attribute " & attr.Name & "='" & attr.Value & "'")) End Sub 'serializer_UnknownAttribute End Class 'Test
using System; using System.Xml; using System.Xml.Serialization; using System.IO; /* The XmlRootAttribute allows you to set an alternate name (PurchaseOrder) of the XML element, the element namespace; by default, the XmlSerializer uses the class name. The attribute also allows you to set the XML namespace for the element. Lastly, the attribute sets the IsNullable property, which specifies whether the xsi:null attribute appears if the class instance is set to a null reference. */ [XmlRootAttribute("PurchaseOrder", Namespace="http://www.cpandl.com", IsNullable = false)] public class PurchaseOrder { public Address ShipTo; public string OrderDate; /* The XmlArrayAttribute changes the XML element name from the default of "OrderedItems" to "Items". */ [XmlArrayAttribute("Items")] public OrderedItem[] OrderedItems; public decimal SubTotal; public decimal ShipCost; public decimal TotalCost; } public class Address { /* The XmlAttribute instructs the XmlSerializer to serialize the Name field as an XML attribute instead of an XML element (the default behavior). */ [XmlAttribute] public string Name; public string Line1; /* Setting the IsNullable property to false instructs the XmlSerializer that the XML attribute will not appear if the City field is set to a null reference. */ [XmlElementAttribute(IsNullable = false)] public string City; public string State; public string Zip; } public class OrderedItem { public string ItemName; public string Description; public decimal UnitPrice; public int Quantity; public decimal LineTotal; /* Calculate is a custom method that calculates the price per item, and stores the value in a field. */ public void Calculate() { LineTotal = UnitPrice * Quantity; } } public class Test { public static void Main() { // Read and write purchase orders. Test t = new Test(); t.CreatePO("po.xml"); t.ReadPO("po.xml"); } private void CreatePO(string filename) { // Create an instance of the XmlSerializer class; // specify the type of object to serialize. XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder)); TextWriter writer = new StreamWriter(filename); PurchaseOrder po=new PurchaseOrder(); // Create an address to ship and bill to. Address billAddress = new Address(); billAddress.Name = "Teresa Atkinson"; billAddress.Line1 = "1 Main St."; billAddress.City = "AnyTown"; billAddress.State = "WA"; billAddress.Zip = "00000"; // Set ShipTo and BillTo to the same addressee. po.ShipTo = billAddress; po.OrderDate = System.DateTime.Now.ToLongDateString(); // Create an OrderedItem object. OrderedItem i1 = new OrderedItem(); i1.ItemName = "Widget S"; i1.Description = "Small widget"; i1.UnitPrice = (decimal) 5.23; i1.Quantity = 3; i1.Calculate(); // Insert the item into the array. OrderedItem [] items = {i1}; po.OrderedItems = items; // Calculate the total cost. decimal subTotal = new decimal(); foreach(OrderedItem oi in items) { subTotal += oi.LineTotal; } po.SubTotal = subTotal; po.ShipCost = (decimal) 12.51; po.TotalCost = po.SubTotal + po.ShipCost; // Serialize the purchase order, and close the TextWriter. serializer.Serialize(writer, po); writer.Close(); } protected void ReadPO(string filename) { // Create an instance of the XmlSerializer class; // specify the type of object to be deserialized. XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder)); /* If the XML document has been altered with unknown nodes or attributes, handle them with the UnknownNode and UnknownAttribute events.*/ serializer.UnknownNode+= new XmlNodeEventHandler(serializer_UnknownNode); serializer.UnknownAttribute+= new XmlAttributeEventHandler(serializer_UnknownAttribute); // A FileStream is needed to read the XML document. FileStream fs = new FileStream(filename, FileMode.Open); // Declare an object variable of the type to be deserialized. PurchaseOrder po; /* Use the Deserialize method to restore the object's state with data from the XML document. */ po = (PurchaseOrder) serializer.Deserialize(fs); // Read the order date. Console.WriteLine ("OrderDate: " + po.OrderDate); // Read the shipping address. Address shipTo = po.ShipTo; ReadAddress(shipTo, "Ship To:"); // Read the list of ordered items. OrderedItem [] items = po.OrderedItems; Console.WriteLine("Items to be shipped:"); foreach(OrderedItem oi in items) { Console.WriteLine("\t"+ oi.ItemName + "\t" + oi.Description + "\t" + oi.UnitPrice + "\t" + oi.Quantity + "\t" + oi.LineTotal); } // Read the subtotal, shipping cost, and total cost. Console.WriteLine("\t\t\t\t\t Subtotal\t" + po.SubTotal); Console.WriteLine("\t\t\t\t\t Shipping\t" + po.ShipCost); Console.WriteLine("\t\t\t\t\t Total\t\t" + po.TotalCost); } protected void ReadAddress(Address a, string label) { // Read the fields of the Address object. Console.WriteLine(label); Console.WriteLine("\t"+ a.Name ); Console.WriteLine("\t" + a.Line1); Console.WriteLine("\t" + a.City); Console.WriteLine("\t" + a.State); Console.WriteLine("\t" + a.Zip ); Console.WriteLine(); } private void serializer_UnknownNode (object sender, XmlNodeEventArgs e) { Console.WriteLine("Unknown Node:" + e.Name + "\t" + e.Text); } private void serializer_UnknownAttribute (object sender, XmlAttributeEventArgs e) { System.Xml.XmlAttribute attr = e.Attr; Console.WriteLine("Unknown attribute " + attr.Name + "='" + attr.Value + "'"); } }
#using <System.Xml.dll> #using <System.dll> using namespace System; using namespace System::Xml; using namespace System::Xml::Serialization; using namespace System::IO; ref class Address; ref class OrderedItem; /* The XmlRootAttribute allows you to set an alternate name (PurchaseOrder) of the XML element, the element namespace; by default, the XmlSerializer uses the class name. The attribute also allows you to set the XML namespace for the element. Lastly, the attribute sets the IsNullable property, which specifies whether the xsi:null attribute appears if the class instance is set to a null reference. */ [XmlRootAttribute("PurchaseOrder",Namespace="http://www.cpandl.com", IsNullable=false)] public ref class PurchaseOrder { public: Address^ ShipTo; String^ OrderDate; /* The XmlArrayAttribute changes the XML element name from the default of "OrderedItems" to "Items". */ [XmlArrayAttribute("Items")] array<OrderedItem^>^OrderedItems; Decimal SubTotal; Decimal ShipCost; Decimal TotalCost; }; public ref class Address { public: /* The XmlAttribute instructs the XmlSerializer to serialize the Name field as an XML attribute instead of an XML element (the default behavior). */ [XmlAttributeAttribute] String^ Name; String^ Line1; /* Setting the IsNullable property to false instructs the XmlSerializer that the XML attribute will not appear if the City field is set to a null reference. */ [XmlElementAttribute(IsNullable=false)] String^ City; String^ State; String^ Zip; }; public ref class OrderedItem { public: String^ ItemName; String^ Description; Decimal UnitPrice; int Quantity; Decimal LineTotal; /* Calculate is a custom method that calculates the price per item, and stores the value in a field. */ void Calculate() { LineTotal = UnitPrice * Quantity; } }; public ref class Test { public: static void main() { // Read and write purchase orders. Test^ t = gcnew Test; t->CreatePO( "po.xml" ); t->ReadPO( "po.xml" ); } private: void CreatePO( String^ filename ) { // Create an instance of the XmlSerializer class; // specify the type of object to serialize. XmlSerializer^ serializer = gcnew XmlSerializer( PurchaseOrder::typeid ); TextWriter^ writer = gcnew StreamWriter( filename ); PurchaseOrder^ po = gcnew PurchaseOrder; // Create an address to ship and bill to. Address^ billAddress = gcnew Address; billAddress->Name = "Teresa Atkinson"; billAddress->Line1 = "1 Main St."; billAddress->City = "AnyTown"; billAddress->State = "WA"; billAddress->Zip = "00000"; // Set ShipTo and BillTo to the same addressee. po->ShipTo = billAddress; po->OrderDate = System::DateTime::Now.ToLongDateString(); // Create an OrderedItem object. OrderedItem^ i1 = gcnew OrderedItem; i1->ItemName = "Widget S"; i1->Description = "Small widget"; i1->UnitPrice = (Decimal)5.23; i1->Quantity = 3; i1->Calculate(); // Insert the item into the array. array<OrderedItem^>^items = {i1}; po->OrderedItems = items; // Calculate the total cost. Decimal subTotal = Decimal(0); System::Collections::IEnumerator^ myEnum = items->GetEnumerator(); while ( myEnum->MoveNext() ) { OrderedItem^ oi = safe_cast<OrderedItem^>(myEnum->Current); subTotal = subTotal + oi->LineTotal; } po->SubTotal = subTotal; po->ShipCost = (Decimal)12.51; po->TotalCost = po->SubTotal + po->ShipCost; // Serialize the purchase order, and close the TextWriter. serializer->Serialize( writer, po ); writer->Close(); } protected: void ReadPO( String^ filename ) { // Create an instance of the XmlSerializer class; // specify the type of object to be deserialized. XmlSerializer^ serializer = gcnew XmlSerializer( PurchaseOrder::typeid ); /* If the XML document has been altered with unknown nodes or attributes, handle them with the UnknownNode and UnknownAttribute events.*/ serializer->UnknownNode += gcnew XmlNodeEventHandler( this, &Test::serializer_UnknownNode ); serializer->UnknownAttribute += gcnew XmlAttributeEventHandler( this, &Test::serializer_UnknownAttribute ); // A FileStream is needed to read the XML document. FileStream^ fs = gcnew FileStream( filename,FileMode::Open ); // Declare an object variable of the type to be deserialized. PurchaseOrder^ po; /* Use the Deserialize method to restore the object's state with data from the XML document. */ po = dynamic_cast<PurchaseOrder^>(serializer->Deserialize( fs )); // Read the order date. Console::WriteLine( "OrderDate: {0}", po->OrderDate ); // Read the shipping address. Address^ shipTo = po->ShipTo; ReadAddress( shipTo, "Ship To:" ); // Read the list of ordered items. array<OrderedItem^>^items = po->OrderedItems; Console::WriteLine( "Items to be shipped:" ); System::Collections::IEnumerator^ myEnum1 = items->GetEnumerator(); while ( myEnum1->MoveNext() ) { OrderedItem^ oi = safe_cast<OrderedItem^>(myEnum1->Current); Console::WriteLine( "\t{0}\t{1}\t{2}\t{3}\t{4}", oi->ItemName, oi->Description, oi->UnitPrice, oi->Quantity, oi->LineTotal ); } Console::WriteLine( "\t\t\t\t\t Subtotal\t{0}", po->SubTotal ); Console::WriteLine( "\t\t\t\t\t Shipping\t{0}", po->ShipCost ); Console::WriteLine( "\t\t\t\t\t Total\t\t{0}", po->TotalCost ); } void ReadAddress( Address^ a, String^ label ) { // Read the fields of the Address object. Console::WriteLine( label ); Console::WriteLine( "\t{0}", a->Name ); Console::WriteLine( "\t{0}", a->Line1 ); Console::WriteLine( "\t{0}", a->City ); Console::WriteLine( "\t{0}", a->State ); Console::WriteLine( "\t{0}", a->Zip ); Console::WriteLine(); } private: void serializer_UnknownNode( Object^ /*sender*/, XmlNodeEventArgs^ e ) { Console::WriteLine( "Unknown Node:{0}\t{1}", e->Name, e->Text ); } void serializer_UnknownAttribute( Object^ /*sender*/, XmlAttributeEventArgs^ e ) { System::Xml::XmlAttribute^ attr = e->Attr; Console::WriteLine( "Unknown attribute {0}='{1}'", attr->Name, attr->Value ); } }; int main() { Test::main(); }
.NET Framework
Supportato in: 4, 3.5, 3.0, 2.0, 1.1, 1.0.NET Framework Client Profile
Supportato in: 4, 3.5 SP1Supportato in:
Windows 7, Windows Vista SP1 o versione successiva, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (componenti di base del server non supportati), Windows Server 2008 R2 (componenti di base del server supportati con SP1 o versione successiva), Windows Server 2003 SP2
.NET Framework non supporta tutte le versioni di ciascuna piattaforma. Per un elenco delle versioni supportate, vedere Requisiti di sistema di .NET Framework.
Questo tipo è thread-safe.
Nota