Classe XmlSerializer
Assembly: System.Xml (in system.xml.dll)
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 un modo 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 Strumento di definizione di schemi XML (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 sono 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 Attributi che controllano la serializzazione XML. 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 Attributi che controllano la serializzazione con codifica SOAP.
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 nidificato nel documento XML principale. Ad esempio, la prima classe nel seguente codice restituisce un'istanza della seconda classe.
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 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 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 Procedura: controllare la serializzazione delle classi derivate.
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 valore integer 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:
System.Xml.Serialization.XmlSerializer(Type)
System.Xml.Serialization.XmlSerializer(Type,String)
Se si utilizza qualsiasi altro costruttore, vengono generate più versioni dello stesso assembly che non vengono mai scaricate e si verificano così una perdita di memoria e un calo di prestazioni. La soluzione più semplice consiste nell'utilizzare uno dei due costruttori sopra indicati. 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. }
Serializzazione di ArrayList e di elenchi generici
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.
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 + "'"); } }
import System.*;
import System.Xml.*;
import System.Xml.Serialization.*;
import 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. */
/** @attribute 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". */
/** @attribute XmlArrayAttribute("Items")
*/
public OrderedItem orderedItems[];
public System.Decimal subTotal;
public System.Decimal shipCost;
public System.Decimal totalCost;
} //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). */
/** @attribute 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. */
/** @attribute XmlElementAttribute(IsNullable = false)
*/
public String city;
public String state;
public String zip;
} //Address
public class OrderedItem
{
public String itemName;
public String description;
public System.Decimal unitPrice;
public int quantity;
public System.Decimal lineTotal;
/* Calculate is a custom method that calculates the price per item,
and stores the value in a field. */
public void Calculate()
{
lineTotal = Decimal.Multiply(unitPrice, Convert.ToDecimal(quantity));
} //Calculate
} //OrderedItem
public class Test
{
public static void main(String[] args)
{
// Read and write purchase orders.
Test t = new Test();
t.CreatePO("po.xml");
t.ReadPO("po.xml");
} //main
private void CreatePO(String fileName)
{
// Create an instance of the XmlSerializer class;
// specify the type of object to serialize.
XmlSerializer serializer =
new XmlSerializer(PurchaseOrder.class.ToType());
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.get_Now().ToLongDateString();
// Create an OrderedItem object.
OrderedItem i1 = new OrderedItem();
i1.itemName = "Widget S";
i1.description = "Small widget";
i1.unitPrice = Convert.ToDecimal(5.23);
i1.quantity = 3;
i1.Calculate();
// Insert the item into the array.
OrderedItem items[] = { i1 };
po.orderedItems = items;
// Calculate the total cost.
System.Decimal subTotal = new System.Decimal();
for (int iCtr = 0; iCtr < items.length; iCtr++) {
OrderedItem oi = items[iCtr];
subTotal = Decimal.Add(subTotal, oi.lineTotal);
}
po.subTotal = subTotal;
po.shipCost = Convert.ToDecimal(12.51);
po.totalCost = Decimal.Add(po.subTotal, po.shipCost);
// Serialize the purchase order, and close the TextWriter.
serializer.Serialize(writer, po);
writer.Close();
} //CreatePO
protected void ReadPO(String fileName)
{
// Create an instance of the XmlSerializer class;
// specify the type of object to be deserialized.
XmlSerializer serializer =
new XmlSerializer(PurchaseOrder.class.ToType());
/* If the XML document has been altered with unknown
nodes or attributes, handle them with the
UnknownNode and UnknownAttribute events.*/
serializer.add_UnknownNode(
new XmlNodeEventHandler(Serializer_UnknownNode));
serializer.add_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:");
for (int iCtr = 0; iCtr < items.length; iCtr++) {
OrderedItem oi = items[iCtr];
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);
} //ReadPO
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();
} //ReadAddress
private void Serializer_UnknownNode(Object sender, XmlNodeEventArgs e)
{
Console.WriteLine("Unknown Node:" + e.get_Name() + "\t" + e.get_Text());
} //Serializer_UnknownNode
private void Serializer_UnknownAttribute(Object sender,
XmlAttributeEventArgs e)
{
System.Xml.XmlAttribute attr = e.get_Attr();
Console.WriteLine("Unknown attribute " + attr.get_Name() + "='"
+ attr.get_Value() + "'");
} //Serializer_UnknownAttribute
} //Test
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.
Riferimenti
Membri XmlSerializerSpazio dei nomi System.Xml.Serialization
Classe XmlAttributeOverrides
Classe XmlAttributes
Classe XmlSerializer
Proprietà XmlAttributes.XmlText
Classe XmlAttributes
Altre risorse
Introduzione alla serializzazione XMLProcedura: specificare un nome di elemento alternativo per un flusso XML
Controllo della serializzazione XML mediante attributi
Esempi di serializzazione XML
Strumento di definizione di schemi XML (Xsd.exe)
Procedura: controllare la serializzazione delle classi derivate
Elemento <dateTimeSerialization>
Elemento <xmlSerializer>
Nota