5 out of 16 rated this helpful - Rate this topic

XmlSerializer Class

Serializes and deserializes objects into and from XML documents. The XmlSerializer enables you to control how objects are encoded into XML.

System.Object
  System.Xml.Serialization.XmlSerializer

Namespace:  System.Xml.Serialization
Assembly:  System.Xml (in System.Xml.dll)
public class XmlSerializer

The XmlSerializer type exposes the following members.

  Name Description
Protected method Supported by the XNA Framework Supported by Portable Class Library XmlSerializer() Infrastructure. Initializes a new instance of the XmlSerializer class.
Public method Supported by the XNA Framework Supported by Portable Class Library XmlSerializer(Type) Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into objects of the specified type.
Public method Supported by the XNA Framework Supported by Portable Class Library XmlSerializer(XmlTypeMapping) Initializes an instance of the XmlSerializer class using an object that maps one type to another.
Public method Supported by the XNA Framework Supported by Portable Class Library XmlSerializer(Type, String) Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into objects of the specified type. Specifies the default namespace for all the XML elements.
Public method Supported by the XNA Framework Supported by Portable Class Library XmlSerializer(Type, Type[]) Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into object of a specified type. If a property or field returns an array, the extraTypes parameter specifies objects that can be inserted into the array.
Public method Supported by the XNA Framework Supported by Portable Class Library XmlSerializer(Type, XmlAttributeOverrides) Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into objects of the specified type. Each object to be serialized can itself contain instances of classes, which this overload can override with other classes.
Public method Supported by the XNA Framework Supported by Portable Class Library XmlSerializer(Type, XmlRootAttribute) Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize an XML document into object of the specified type. It also specifies the class to use as the XML root element.
Public method Supported by the XNA Framework Supported by Portable Class Library XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String) Initializes a new instance of the XmlSerializer class that can serialize objects of type Object into XML document instances, and deserialize XML document instances into objects of type Object. Each object to be serialized can itself contain instances of classes, which this overload overrides with other classes. This overload also specifies the default namespace for all the XML elements and the class to use as the XML root element.
Public method XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String) Initializes a new instance of the XmlSerializer class that can serialize objects of type Object into XML document instances, and deserialize XML document instances into objects of type Object. Each object to be serialized can itself contain instances of classes, which this overload overrides with other classes. This overload also specifies the default namespace for all the XML elements and the class to use as the XML root element.
Public method XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String, Evidence) Infrastructure. Obsolete. Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML document instances, and deserialize XML document instances into objects of the specified type. This overload allows you to supply other types that can be encountered during a serialization or deserialization operation, as well as a default namespace for all XML elements, the class to use as the XML root element, its location, and credentials required for access.
Top
  Name Description
Public method Supported by the XNA Framework Supported by Portable Class Library CanDeserialize Gets a value that indicates whether this XmlSerializer can deserialize a specified XML document.
Protected method CreateReader Infrastructure. Returns an object used to read the XML document to be serialized.
Protected method CreateWriter Infrastructure. When overridden in a derived class, returns a writer used to serialize the object.
Public method Supported by the XNA Framework Supported by Portable Class Library Deserialize(Stream) Deserializes the XML document contained by the specified Stream.
Public method Supported by the XNA Framework Supported by Portable Class Library Deserialize(TextReader) Deserializes the XML document contained by the specified TextReader.
Public method Supported by the XNA Framework Supported by Portable Class Library Deserialize(XmlReader) Deserializes the XML document contained by the specified XmlReader.
Protected method Deserialize(XmlSerializationReader) Infrastructure. Deserializes the XML document contained by the specified XmlSerializationReader.
Public method Supported by the XNA Framework Deserialize(XmlReader, String) Deserializes the XML document contained by the specified XmlReader and encoding style.
Public method Deserialize(XmlReader, XmlDeserializationEvents) Deserializes an XML document contained by the specified XmlReader and allows the overriding of events that occur during deserialization.
Public method Deserialize(XmlReader, String, XmlDeserializationEvents) Infrastructure. Deserializes the object using the data contained by the specified XmlReader.
Public method Supported by the XNA Framework Supported by Portable Class Library Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Supported by the XNA Framework Supported by Portable Class Library Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method Static member Supported by Portable Class Library FromMappings(XmlMapping[]) Infrastructure. Returns an array of XmlSerializer objects created from an array of XmlTypeMapping objects.
Public method Static member FromMappings(XmlMapping[], Evidence) Obsolete. Returns an instance of the XmlSerializer class created from mappings of one XML type to another.
Public method Static member Supported by Portable Class Library FromMappings(XmlMapping[], Type) Infrastructure. Returns an instance of the XmlSerializer class from the specified mappings.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library FromTypes Returns an array of XmlSerializer objects created from an array of types.
Public method Static member GenerateSerializer(Type[], XmlMapping[]) Infrastructure. Returns an assembly that contains custom-made serializers used to serialize or deserialize the specified type or types, using the specified mappings.
Public method Static member GenerateSerializer(Type[], XmlMapping[], CompilerParameters) Infrastructure. Returns an assembly that contains custom-made serializers used to serialize or deserialize the specified type or types, using the specified mappings and compiler settings and options.
Public method Supported by the XNA Framework Supported by Portable Class Library GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method Supported by the XNA Framework Supported by Portable Class Library GetType Gets the Type of the current instance. (Inherited from Object.)
Public method Static member GetXmlSerializerAssemblyName(Type) Returns the name of the assembly that contains one or more versions of the XmlSerializer especially created to serialize or deserialize the specified type.
Public method Static member GetXmlSerializerAssemblyName(Type, String) Returns the name of the assembly that contains the serializer for the specified type in the specified namespace.
Protected method Supported by the XNA Framework Supported by Portable Class Library MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method Serialize(Object, XmlSerializationWriter) Infrastructure. Serializes the specified Object and writes the XML document to a file using the specified XmlSerializationWriter.
Public method Supported by the XNA Framework Supported by Portable Class Library Serialize(Stream, Object) Serializes the specified Object and writes the XML document to a file using the specified Stream.
Public method Supported by the XNA Framework Supported by Portable Class Library Serialize(TextWriter, Object) Serializes the specified Object and writes the XML document to a file using the specified TextWriter.
Public method Supported by the XNA Framework Supported by Portable Class Library Serialize(XmlWriter, Object) Serializes the specified Object and writes the XML document to a file using the specified XmlWriter.
Public method Supported by the XNA Framework Supported by Portable Class Library Serialize(Stream, Object, XmlSerializerNamespaces) Serializes the specified Object and writes the XML document to a file using the specified Streamthat references the specified namespaces.
Public method Supported by the XNA Framework Supported by Portable Class Library Serialize(TextWriter, Object, XmlSerializerNamespaces) Serializes the specified Object and writes the XML document to a file using the specified TextWriter and references the specified namespaces.
Public method Supported by the XNA Framework Supported by Portable Class Library Serialize(XmlWriter, Object, XmlSerializerNamespaces) Serializes the specified Object and writes the XML document to a file using the specified XmlWriter and references the specified namespaces.
Public method Supported by the XNA Framework Serialize(XmlWriter, Object, XmlSerializerNamespaces, String) Serializes the specified object and writes the XML document to a file using the specified XmlWriter and references the specified namespaces and encoding style.
Public method Serialize(XmlWriter, Object, XmlSerializerNamespaces, String, String) Serializes the specified Object and writes the XML document to a file using the specified XmlWriter, XML namespaces, and encoding.
Public method Supported by the XNA Framework Supported by Portable Class Library ToString Returns a string that represents the current object. (Inherited from Object.)
Top
  Name Description
Public event Supported by the XNA Framework UnknownAttribute Occurs when the XmlSerializer encounters an XML attribute of unknown type during deserialization.
Public event Supported by the XNA Framework UnknownElement Occurs when the XmlSerializer encounters an XML element of unknown type during deserialization.
Public event Supported by the XNA Framework UnknownNode Occurs when the XmlSerializer encounters an XML node of unknown type during deserialization.
Public event Supported by the XNA Framework UnreferencedObject Occurs during deserialization of a SOAP-encoded XML stream, when the XmlSerializer encounters a recognized type that is not used or is unreferenced.
Top

XML serialization is the process of converting an object's public properties and fields to a serial format (in this case, XML) for storage or transport. Deserialization re-creates the object in its original state from the XML output. You can think of serialization as a way of saving the state of an object into a stream or buffer. For example, ASP.NET uses the XmlSerializer class to encode XML Web service messages.

The data in your objects is described using programming language constructs like classes, fields, properties, primitive types, arrays, and even embedded XML in the form of XmlElement or XmlAttribute objects. You have the option of creating your own classes, annotated with attributes, or using the XML Schema Definition Tool (Xsd.exe) to generate the classes based on an existing XML Schema definition (XSD) document. If you have an XML Schema, you can run the Xsd.exe to produce a set of classes that are strongly typed to the schema and annotated with attributes to adhere to the schema when serialized.

To transfer data between objects and XML requires a mapping from the programming language constructs to XML schema and from the XML schema to the programming language constructs. The XmlSerializer and related tools like Xsd.exe provide the bridge between these two technologies at both design time and runtime. At design time, use the Xsd.exe to produce an XML schema document (.xsd) from your custom classes or to produce classes from a given schema. In either case, the classes are annotated with custom attributes to instruct the XmlSerializer how to map between the XML schema system and the common language runtime. At runtime, instances of the classes can be serialized into XML documents that follow the given schema. Likewise, these XML documents can be deserialized into runtime objects. Note that the XML schema is optional, and not required at design time or runtime.

Controlling Generated XML

To control the generated XML, you can apply special attributes to classes and members. For example, to specify a different XML element name, apply an XmlElementAttribute to a public field or property, and set the ElementName property. For a complete list of similar attributes, see Attributes That Control XML Serialization. You can also implement the IXmlSerializable interface to control the XML output.

If the XML generated must conform to section 5 of the World Wide Consortium (www.w3.org) document, "Simple Object Access Protocol (SOAP) 1.1", you must construct the XmlSerializer with an XmlTypeMapping. To further control the encoded SOAP XML, use the attributes listed in Attributes That Control Encoded SOAP Serialization.

With the XmlSerializer you can take advantage of working with strongly typed classes and still have the flexibility of XML. Using fields or properties of type XmlElement, XmlAttribute or XmlNode in your strongly typed classes, you can read parts of the XML document directly into XML objects.

If you work with extensible XML schemas, you can also use the XmlAnyElementAttribute and XmlAnyAttributeAttribute attributes to serialize and deserialize elements or attributes that are not found in the original schema. To use the objects, apply an XmlAnyElementAttribute to a field that returns an array of XmlElement objects, or apply an XmlAnyAttributeAttribute to a field that returns an array of XmlAttribute objects.

If a property or field returns a complex object (such as an array or a class instance), the XmlSerializer converts it to an element nested within the main XML document. For example, the first class in the following code returns an instance of the second class.

public class MyClass
{
    public MyObject MyObjectProperty;
}
public class MyObject
{
    public string ObjectName;
}

The serialized, XML output looks like this:

<MyClass>
  <MyObjectProperty>
  <ObjectName>My String</ObjectName>
  </MyObjectProperty>
</MyClass>

If a schema includes an element that is optional (minOccurs = '0'), or if the schema includes a default value, you have two options. One option is to use System.ComponentModel.DefaultValueAttribute to specify the default value, as shown in the following code.

public class PurchaseOrder
{
    [System.ComponentModel.DefaultValueAttribute ("2002")]
    public string Year;
}

Another option is to use a special pattern to create a Boolean field recognized by the XmlSerializer, and to apply the XmlIgnoreAttribute to the field. The pattern is created in the form of propertyNameSpecified. For example, if there is a field named "MyFirstName" you would also create a field named "MyFirstNameSpecified" that instructs the XmlSerializer whether to generate the XML element named "MyFirstName". This is shown in the following example.

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;
}

Overriding Default Serialization

You can also override the serialization of any set of objects and their fields and properties by creating one of the appropriate attributes, and adding it to an instance of the XmlAttributes class. Overriding serialization in this way has two uses: first, you can control and augment the serialization of objects found in a DLL, even if you do not have access to the source; second, you can create one set of serializable classes, but serialize the objects in multiple ways. For more details, see the XmlAttributeOverrides class and How to: Control Serialization of Derived Classes.

To serialize an object, call the Serialize method. To deserialize an object, call the Deserialize method.

To add XML namespaces to an XML document, see XmlSerializerNamespaces.

Note Note

The XmlSerializer gives special treatment to classes that implement IEnumerable or ICollection. A class that implements IEnumerable must implement a public Add method that takes a single parameter. The Add method's parameter must be of the same type as is returned from the Current property on the value returned from GetEnumerator, or one of that type's bases. A class that implements ICollection (such as CollectionBase) in addition to IEnumerable must have a public Item indexed property (indexer in C#) that takes an integer, and it must have a public Count property of type integer. The parameter to the Add method must be the same type as is returned from the Item property, or one of that type's bases. For classes that implement ICollection, values to be serialized are retrieved from the indexed Item property, not by calling GetEnumerator.

You must have permission to write to the temporary directory (as defined by the TEMP environment variable) to deserialize an object.

Dynamically Generated Assemblies

To increase performance, the XML serialization infrastructure dynamically generates assemblies to serialize and deserialize specified types. The infrastructure finds and reuses those assemblies. This behavior occurs only when using the following constructors:

XmlSerializer.XmlSerializer(Type)

XmlSerializer.XmlSerializer(Type, String)

If you use any of the other constructors, multiple versions of the same assembly are generated and never unloaded, which results in a memory leak and poor performance. The easiest solution is to use one of the previously mentioned two constructors. Otherwise, you must cache the assemblies in a Hashtable, as shown in the following example.

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.
}

Serialization of ArrayList and Generic List

The XmlSerializer cannot serialize or deserialize the following:

Serialization of Enumerations of Unsigned Long

The XmlSerializer cannot be instantiated to serialize an enumeration if the following conditions are true: The enumeration is of type unsigned long (ulong in C#) and the enumeration contains any member with a value larger than 9,223,372,036,854,775,807. For example, the following cannot be serialized.

public enum LargeNumbers: ulong
{
    a = 9223372036854775808
}
// At runtime, the following code will fail.
xmlSerializer mySerializer=new XmlSerializer(typeof(LargeNumbers));

Objects marked with the Obsolete Attribute no longer serialized

In the  the XmlSerializer class no longer serializes objects that are marked as [Obsolete].

The following example contains two main classes: PurchaseOrder and Test. The PurchaseOrder class contains information about a single purchase. The Test class contains the methods that create the purchase order, and that read the created purchase order.


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 + "'");
   }
}


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

This type is thread safe.

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Discussion of XMLSerializer limitations
FYI there is an excellent discussion here: http://stackoverflow.com/questions/109318/using-net-what-limitations-if-any-are-there-in-using-the-xmlserializer on the limitations of XMLSerializer.
Code for Putting XmlSerialiser in a HashTable appears wrong.
Hashtable serializers = new Hashtable();// Use the constructor that takes a type and XmlRootAttribute.

// the following line would appear to be unnecessary
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;
}
  // the following lines would appear to be unnecessary
else
{
    // Use the serializer to serialize, or deserialize.
}
bordegas program serial

seriali xml
program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; // cal afegir els dos Namespaces per serialitzar i tractar  fitxers
using System.Xml.Serialization;
using System.Text;
   
namespace serialitzacioSoap
{
    class Program
    {
        static void Main(string[] args)
        {
            string fitxer = @"C:\temp\prova.xml";
            Equip e = new Equip("Barca", 100);
            Equip ee = new Equip("madrid", 90);
            Equip eee = new Equip("valencia", 80);
            guardar(e,ee,eee, fitxer);
            Console.WriteLine("s'han guardat correctament els equips {0:2d},{1:2d},{2:2d}",e.Nom,ee.Nom,eee.Nom);
            Console.WriteLine(" Final... apreti intro per sortir ");
            Console.ReadLine();
        }
        static void guardar(Equip xe, Equip xee,Equip xeee, string xfitxer)
        {
            string fitxer = @"C:\temp\prova.xml";
            // creem un objecte XmlSerializer que sera el que guardara
            // les dades del equip, li passem el typeof(Equip) per tal que
            // sapigi quina informacio té equip
            XmlSerializer xs = new XmlSerializer(typeof(Equip));
            // creem un Filestream  del fitxer
            if (File.Exists(fitxer))
            {
                File.Delete(fitxer);
            }
            FileStream fs = new FileStream(xfitxer,
                FileMode.Append, FileAccess.Write);
            // aqui guardem al textwriter l'objecte xe rebut com argument
            xs.Serialize(fs, xe);
            xs.Serialize(fs, xee);
            xs.Serialize(fs, xeee);
            fs.Flush(); // tenquem els fitxers
            fs.Close();
            fs.Dispose();
        }
        static Equip Recuperar(string xfitxer)
        {
            Equip e = null;
            // creem un XmlSerializer que sera el que recuperar l'objecte de tipus Equip
            // typeof equip indica a xs que recuperarà equip, amb nom (string) i punts (integer)
            XmlSerializer xs = new XmlSerializer(typeof(Equip));
            // obrim el fitxer que conté el xml
            FileStream fs = new FileStream(xfitxer, FileMode.Open, FileAccess.Read);
            // per recuperar l'equip, fem servir Deserialize, que retorna UN OBJECT
            // per tant cal fer un casting a Equip per assignar-lo a e
            e = (Equip)xs.Deserialize(fs);
            fs.Close();// tenquem els fitxers
            fs.Dispose();
            return e;
        }
    }
}
--------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
namespace serialitzacioSoap
{
    [Serializable] // cal posar aixo per fer la classe Serializable
        // ha de ser public
    public class Equip
    {
        private string _nom;
        private int _punts;
        public string Nom
        {
            get { return _nom; }
            set { _nom = value; }
        }
        public int Punts
        {
            get { return _punts; }
            set { _punts = value; }
        }
        public Equip()
        {
            this.Nom = "";
            this.Punts = 0;
        }
        public Equip(string xnom, int xpunts)
        {
            this.Nom = xnom;
            this.Punts = xpunts;
        }
        public override string ToString()
        {
            string cad = string.Format("{0,10} {1,3:d}", this.Nom, this.Punts);
            return cad;
        }
    }
}
--------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------
seril soap
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Soap;
namespace serialitzacioSoap
{
    class Program
    {
        static void Main(string[] args)
        {
            string fitxer = @"C:\temp\prova.soap";
            Equip e = new Equip("Barca", 1330);
            guardar(e, fitxer);
            Equip e2 = Recuperar(fitxer);
            Console.WriteLine("{0}", e2.ToString());
            Console.WriteLine(" Final... apreti intro per sortir ");
            Console.ReadLine();
        }
        static void guardar(Equip xe, string xfitxer)
        {
            // creem un objecte SoapFormatter que sera el que guardara
            // les dades del equip,
            SoapFormatter sf = new SoapFormatter();
            // creem un filestream associat al fitxer
            FileStream fs = new FileStream(xfitxer,
                FileMode.Create, FileAccess.Write);
            // aqui guardem al filestream l'objecte xe rebut com argument
            sf.Serialize(fs, xe);
            fs.Flush(); // tenquem els fitxers
            fs.Close();
            fs.Dispose();
        }
        static Equip Recuperar(string xfitxer)
        {
            Equip e = null;
            // creem un SoapFormatter que sera el que recuperar l'objecte de tipus Equip
            SoapFormatter sf = new SoapFormatter();
            // obrim el fitxer que conté el xml
            FileStream fs = new FileStream(xfitxer, FileMode.Open, FileAccess.Read);
            // per recuperar l'equip, fem servir Deserialize, que retorna UN OBJECT
            // per tant cal fer un casting a Equip per assignar-lo a e
            e = (Equip)sf.Deserialize(fs);
            fs.Close();// tenquem els fitxers
            fs.Dispose();
            return e;
        }
    }
}
--------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------
serial bin
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;// afegim el namespace IO I
// el de Serialization.Formatters.Binary
using System.Runtime.Serialization.Formatters.Binary;
namespace serialitzacioSoap
{
    class Program
    {
        static void Main(string[] args)
        {
            string fitxer = @"C:\temp\provabin.dat";
            Equip e = new Equip("Barca", 122);
            guardar(e, fitxer);
            Equip e2 = Recuperar(fitxer);
            Console.WriteLine("{0}", e2.ToString());
            Console.WriteLine(" Final... apreti intro per sortir ");
            Console.ReadLine();
        }
        static void guardar(Equip xe, string xfitxer)
        {
            // creem un objecte BinaryFormatter que sera el que guardara
            // les dades del equip
            BinaryFormatter bf = new BinaryFormatter();
            // creem un textWriter que associem al StreamWriter del fitxer
            FileStream fs = new FileStream(xfitxer, FileMode.Create, FileAccess.Write);
            // aqui guardem al textwriter l'objecte xe rebut com argument
            bf.Serialize(fs, xe);
            fs.Flush(); // tenquem els fitxers
            fs.Close();
            fs.Dispose();
        }
        static Equip Recuperar(string xfitxer)
        {
            Equip e = null;
            // creem un binaryFormatter que sera el que recuperar l'objecte de tipus Equip
            // typeof equip indica a xs que recuperarà equip, amb nom (string) i punts (integer)
            BinaryFormatter bf = new BinaryFormatter();
            // obrim el fitxer que conté el xml
            FileStream fs = new FileStream(xfitxer, FileMode.Open, FileAccess.Read);
            // per recuperar l'equip, fem servir Deserialize, que retorna UN OBJECT
            // per tant cal fer un casting a Equip per assignar-lo a e
            e = (Equip)bf.Deserialize(fs);
            fs.Close();// tenquem els fitxers
            fs.Dispose();
            return e;
        }
    }
}
program seriali xml and mes

seriali xml
program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; // cal afegir els dos Namespaces per serialitzar i tractar  fitxers
using System.Xml.Serialization;
using System.Text;
   
namespace serialitzacioSoap
{
    class Program
    {
        static void Main(string[] args)
        {
            string fitxer = @"C:\temp\prova.xml";
            Equip e = new Equip("Barca", 100);
            Equip ee = new Equip("madrid", 90);
            Equip eee = new Equip("valencia", 80);
            guardar(e,ee,eee, fitxer);
            Console.WriteLine("s'han guardat correctament els equips {0:2d},{1:2d},{2:2d}",e.Nom,ee.Nom,eee.Nom);
            Console.WriteLine(" Final... apreti intro per sortir ");
            Console.ReadLine();
        }
        static void guardar(Equip xe, Equip xee,Equip xeee, string xfitxer)
        {
            string fitxer = @"C:\temp\prova.xml";
            // creem un objecte XmlSerializer que sera el que guardara
            // les dades del equip, li passem el typeof(Equip) per tal que
            // sapigi quina informacio té equip
            XmlSerializer xs = new XmlSerializer(typeof(Equip));
            // creem un Filestream  del fitxer
            if (File.Exists(fitxer))
            {
                File.Delete(fitxer);
            }
            FileStream fs = new FileStream(xfitxer,
                FileMode.Append, FileAccess.Write);
            // aqui guardem al textwriter l'objecte xe rebut com argument
            xs.Serialize(fs, xe);
            xs.Serialize(fs, xee);
            xs.Serialize(fs, xeee);
            fs.Flush(); // tenquem els fitxers
            fs.Close();
            fs.Dispose();
        }
        static Equip Recuperar(string xfitxer)
        {
            Equip e = null;
            // creem un XmlSerializer que sera el que recuperar l'objecte de tipus Equip
            // typeof equip indica a xs que recuperarà equip, amb nom (string) i punts (integer)
            XmlSerializer xs = new XmlSerializer(typeof(Equip));
            // obrim el fitxer que conté el xml
            FileStream fs = new FileStream(xfitxer, FileMode.Open, FileAccess.Read);
            // per recuperar l'equip, fem servir Deserialize, que retorna UN OBJECT
            // per tant cal fer un casting a Equip per assignar-lo a e
            e = (Equip)xs.Deserialize(fs);
            fs.Close();// tenquem els fitxers
            fs.Dispose();
            return e;
        }
    }
}
--------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
namespace serialitzacioSoap
{
    [Serializable] // cal posar aixo per fer la classe Serializable
        // ha de ser public
    public class Equip
    {
        private string _nom;
        private int _punts;
        public string Nom
        {
            get { return _nom; }
            set { _nom = value; }
        }
        public int Punts
        {
            get { return _punts; }
            set { _punts = value; }
        }
        public Equip()
        {
            this.Nom = "";
            this.Punts = 0;
        }
        public Equip(string xnom, int xpunts)
        {
            this.Nom = xnom;
            this.Punts = xpunts;
        }
        public override string ToString()
        {
            string cad = string.Format("{0,10} {1,3:d}", this.Nom, this.Punts);
            return cad;
        }
    }
}
--------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------
seril soap
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Soap;
namespace serialitzacioSoap
{
    class Program
    {
        static void Main(string[] args)
        {
            string fitxer = @"C:\temp\prova.soap";
            Equip e = new Equip("Barca", 1330);
            guardar(e, fitxer);
            Equip e2 = Recuperar(fitxer);
            Console.WriteLine("{0}", e2.ToString());
            Console.WriteLine(" Final... apreti intro per sortir ");
            Console.ReadLine();
        }
        static void guardar(Equip xe, string xfitxer)
        {
            // creem un objecte SoapFormatter que sera el que guardara
            // les dades del equip,
            SoapFormatter sf = new SoapFormatter();
            // creem un filestream associat al fitxer
            FileStream fs = new FileStream(xfitxer,
                FileMode.Create, FileAccess.Write);
            // aqui guardem al filestream l'objecte xe rebut com argument
            sf.Serialize(fs, xe);
            fs.Flush(); // tenquem els fitxers
            fs.Close();
            fs.Dispose();
        }
        static Equip Recuperar(string xfitxer)
        {
            Equip e = null;
            // creem un SoapFormatter que sera el que recuperar l'objecte de tipus Equip
            SoapFormatter sf = new SoapFormatter();
            // obrim el fitxer que conté el xml
            FileStream fs = new FileStream(xfitxer, FileMode.Open, FileAccess.Read);
            // per recuperar l'equip, fem servir Deserialize, que retorna UN OBJECT
            // per tant cal fer un casting a Equip per assignar-lo a e
            e = (Equip)sf.Deserialize(fs);
            fs.Close();// tenquem els fitxers
            fs.Dispose();
            return e;
        }
    }
}
--------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------
serial bin
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;// afegim el namespace IO I
// el de Serialization.Formatters.Binary
using System.Runtime.Serialization.Formatters.Binary;
namespace serialitzacioSoap
{
    class Program
    {
        static void Main(string[] args)
        {
            string fitxer = @"C:\temp\provabin.dat";
            Equip e = new Equip("Barca", 122);
            guardar(e, fitxer);
            Equip e2 = Recuperar(fitxer);
            Console.WriteLine("{0}", e2.ToString());
            Console.WriteLine(" Final... apreti intro per sortir ");
            Console.ReadLine();
        }
        static void guardar(Equip xe, string xfitxer)
        {
            // creem un objecte BinaryFormatter que sera el que guardara
            // les dades del equip
            BinaryFormatter bf = new BinaryFormatter();
            // creem un textWriter que associem al StreamWriter del fitxer
            FileStream fs = new FileStream(xfitxer, FileMode.Create, FileAccess.Write);
            // aqui guardem al textwriter l'objecte xe rebut com argument
            bf.Serialize(fs, xe);
            fs.Flush(); // tenquem els fitxers
            fs.Close();
            fs.Dispose();
        }
        static Equip Recuperar(string xfitxer)
        {
            Equip e = null;
            // creem un binaryFormatter que sera el que recuperar l'objecte de tipus Equip
            // typeof equip indica a xs que recuperarà equip, amb nom (string) i punts (integer)
            BinaryFormatter bf = new BinaryFormatter();
            // obrim el fitxer que conté el xml
            FileStream fs = new FileStream(xfitxer, FileMode.Open, FileAccess.Read);
            // per recuperar l'equip, fem servir Deserialize, que retorna UN OBJECT
            // per tant cal fer un casting a Equip per assignar-lo a e
            e = (Equip)bf.Deserialize(fs);
            fs.Close();// tenquem els fitxers
            fs.Dispose();
            return e;
        }
    }
}
Something that needs investigation

"You must have permission to write to the temporary directory (as defined by the TEMP environment variable) to deserialize an object."

If you are a user with restricted rights (not an administrator)(win server 2003) and you use in your application XmlSerializer then it is possible that you receive an exception (and it is even posssible that crc.exe crashes).
 In windows if show hidden folders is NOT active (hidden folders are not visible). While the program closes and the user logs out from windows xmlserializer tries to dynamically compile a dll in the temporary folder. This process either fails, or the dll is created but is not readable by the application that needs it. At this point it's possible that CSC.exe crashses along with the application.

List<T> Serialization.

Hello.

First I want to say a word about PapaJ's comment. In article it is said that the Arrays of Lists can't be serialized, not Lists. 

Now I would like to show my way to serialize the List<T> object. I use it in my little project few days ago.

I've got two classes

First class Account:

  

[Serializable]

public class Account
    {
    
        [XmlAttribute("UserName")]
        public string UserName { get; set; }
      
        [XmlAttribute("UserEmail")]
        public string UserEmail { get; set; }
        [XmlAttribute("UserPass")]
        public string UserPass { get; set; }
        [XmlArray]
        public List<Character> UserCharacters = new List<Character>();
      
//I've cut rest of the body to safe a place.
}
  
    
      
    

Second class Character:

[Serializable]
public class Character
    {
        #region Stats
        [XmlAttribute("Name")]
        public string Name { get; set; }
        [XmlAttribute("Level")]
        public UInt16 Level { get; set; }
        [XmlAttribute("Experiance")]
        public UInt32 Experiance { get; set; }
        [XmlArray]
        public List<uint> Items;
        #endregion
}
  
    

   

When I serialize the Account class it also serialize the List<Character> which is a field in Account class. Xml file looks then like that:

<User xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" UserName="Arche" UserEmail="arche89@gmail.com" UserPass="'?o?q?8K?t'???<m??k?">
<UserCharacters>
   <Character Name="Astamo" Level="0" Experiance="0"/>
   <Character Name="Arche" Level="34" Experiance="35465"/>
</UserCharacters>
</User>


Thanks for reading.
A. Michajluk
    
  
Quick remarks to keep in mind
  1. XmlSerializer will call property setters when deserializing the property.
  2. XMlSerializer does not serialize internal members.
  3. To avoid serialization of public property use [XmlIgnore] attribute.
  4. If property setter is private then XmlSerializer will generate run time exception. However if property setter does not exist then it will not generate exception.
  5. Nullable types with null value gets serialized as <MyProperty p2:nil="true" xmlns:p2="http://www.w3.org/2001/XMLSchema-instance" />.
  6. Null property values for non-nullable types does not generate XML element.
  7. If there are extra elements in XML without corresponding properties then they are ignored.
  8. For value types if XML element does not exist then they are set to their field initialization value.
  9. XML serializer accepts strings formatted with "'yyyy'-'MM'-'dd'T'HH': 'mm': 'ss.fffffff'Z'" for deserializing. Strings compatible to InvariantCulture like "1/31/2011 2:23 PM" will generate run time error.
How to Serialize an ArrayLists
$0$0 $0
The documentation above is not exactly correct, you can serialize an ArrayList if you add types that the ArrayList points to a list of types: 

    Shared Sub Save(ByRef object As myObject)
        Try
            Dim objStreamWriter As New StreamWriter("object.xml")

            Dim extraTypes(0) As Type
            extraTypes(0) = GetType(PointedToType)

            Dim x As New XmlSerializer(object.GetType, extraTypes)
            x.Serialize(objStreamWriter, object)

            objStreamWriter.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
    Shared Function Load() As myObject
        Try
            Dim objStreamReader As New StreamReader("object.xml")
            Dim extraTypes(0) As Type
            extraTypes(0) = GetType(PointedToType)

            Dim x As New XmlSerializer(GetType(myObject), extraTypes)
            Dim object As New myObject
            object = x.Deserialize(objStreamReader)

            objStreamReader.Close()
            Return object 
        Catch ex As Exception
            Throw ex
        End Try
    End Function

I gleaned this information by reading artical by Sheo Narayan at http://www.dotnetfunda.com/articles/article123.aspx

Jacob Christ

insertmyfirstnamehere@pontech.com
$0
$0$0 $0