XmlSerializer Class

Definition

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

C#
public class XmlSerializer
Inheritance
XmlSerializer

Examples

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.

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

Remarks

For more information about this API, see Supplemental API remarks for XmlSerializer.

Constructors

XmlSerializer()

Initializes a new instance of the XmlSerializer class.

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.

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.

XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String, Evidence)
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.

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.

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.

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.

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.

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.

XmlSerializer(XmlTypeMapping)

Initializes an instance of the XmlSerializer class using an object that maps one type to another.

Methods

CanDeserialize(XmlReader)

Gets a value that indicates whether this XmlSerializer can deserialize a specified XML document.

CreateReader()

Returns an object used to read the XML document to be serialized.

CreateWriter()

When overridden in a derived class, returns a writer used to serialize the object.

Deserialize(Stream)

Deserializes the XML document contained by the specified Stream.

Deserialize(TextReader)

Deserializes the XML document contained by the specified TextReader.

Deserialize(XmlReader, String, XmlDeserializationEvents)

Deserializes the object using the data contained by the specified XmlReader.

Deserialize(XmlReader, String)

Deserializes the XML document contained by the specified XmlReader and encoding style.

Deserialize(XmlReader, XmlDeserializationEvents)

Deserializes an XML document contained by the specified XmlReader and allows the overriding of events that occur during deserialization.

Deserialize(XmlReader)

Deserializes the XML document contained by the specified XmlReader.

Deserialize(XmlSerializationReader)

Deserializes the XML document contained by the specified XmlSerializationReader.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
FromMappings(XmlMapping[], Evidence)
Obsolete.

Returns an instance of the XmlSerializer class created from mappings of one XML type to another.

FromMappings(XmlMapping[], Type)

Returns an instance of the XmlSerializer class from the specified mappings.

FromMappings(XmlMapping[])

Returns an array of XmlSerializer objects created from an array of XmlTypeMapping objects.

FromTypes(Type[])

Returns an array of XmlSerializer objects created from an array of types.

GenerateSerializer(Type[], XmlMapping[], CompilerParameters)

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.

GenerateSerializer(Type[], XmlMapping[])

Returns an assembly that contains custom-made serializers used to serialize or deserialize the specified type or types, using the specified mappings.

GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
GetXmlSerializerAssemblyName(Type, String)

Returns the name of the assembly that contains the serializer for the specified type in the specified namespace.

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.

MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
Serialize(Object, XmlSerializationWriter)

Serializes the specified Object and writes the XML document to a file using the specified XmlSerializationWriter.

Serialize(Stream, Object, XmlSerializerNamespaces)

Serializes the specified Object and writes the XML document to a file using the specified Stream that references the specified namespaces.

Serialize(Stream, Object)

Serializes the specified Object and writes the XML document to a file using the specified Stream.

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.

Serialize(TextWriter, Object)

Serializes the specified Object and writes the XML document to a file using the specified TextWriter.

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.

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.

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.

Serialize(XmlWriter, Object)

Serializes the specified Object and writes the XML document to a file using the specified XmlWriter.

ToString()

Returns a string that represents the current object.

(Inherited from Object)

Events

UnknownAttribute

Occurs when the XmlSerializer encounters an XML attribute of unknown type during deserialization.

UnknownElement

Occurs when the XmlSerializer encounters an XML element of unknown type during deserialization.

UnknownNode

Occurs when the XmlSerializer encounters an XML node of unknown type during deserialization.

UnreferencedObject

Occurs during deserialization of a SOAP-encoded XML stream, when the XmlSerializer encounters a recognized type that is not used or is unreferenced.

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0

Thread Safety

This type is thread safe.

See also