XmlSerializer.Serialize Method

Definition

Serializes an object into an XML document.

Overloads

Serialize(XmlWriter, Object)

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

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(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(Object, XmlSerializationWriter)

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

Serialize(TextWriter, Object)

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

Serialize(Stream, Object)

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

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(XmlWriter, Object)

Source:
XmlSerializer.cs
Source:
XmlSerializer.cs
Source:
XmlSerializer.cs

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

C#
public void Serialize(System.Xml.XmlWriter xmlWriter, object o);
C#
public void Serialize(System.Xml.XmlWriter xmlWriter, object? o);

Parameters

xmlWriter
XmlWriter

The XmlWriter used to write the XML document.

o
Object

The Object to serialize.

Exceptions

An error occurred during serialization. The original exception is available using the InnerException property.

Examples

The following example serializes an object using an XmlWriter.

C#
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

// This is the class that will be serialized.
public class OrderedItem4
{
    public string ItemName;
    public string Description;
    public decimal UnitPrice;
    public int Quantity;
    public decimal LineTotal;
    // A custom method used to calculate price per item.
    public void Calculate()
    {
        LineTotal = UnitPrice * Quantity;
    }
}

public class Test4
{
    public static void Main()
    {
        Test4 t = new();
        // Write a purchase order.
        t.SerializeObject("simple.xml");
    }

    private void SerializeObject(string filename)
    {
        Console.WriteLine("Writing With XmlTextWriter");

        XmlSerializer serializer = new(typeof(OrderedItem4));
        OrderedItem4 i = new()
        {
            ItemName = "Widget",
            Description = "Regular Widget",
            Quantity = 10,
            UnitPrice = (decimal)2.30
        };
        i.Calculate();
        // Create an XmlTextWriter using a FileStream.
        Stream fs = new FileStream(filename, FileMode.Create);
        XmlTextWriter writer = new(fs, Encoding.Unicode);
        // Serialize using the XmlTextWriter.
        serializer.Serialize(writer, i);
        writer.Close();
    }
}
XML
<?xml version="1.0"?>
 <OrderedItem xmlns:inventory="http://www.cpandl.com" xmlns:money="http://www.cohowinery.com">
   <inventory:ItemName>Widget</inventory:ItemName>
   <inventory:Description>Regular Widget</inventory:Description>
   <money:UnitPrice>2.3</money:UnitPrice>
   <inventory:Quantity>10</inventory:Quantity>
   <money:LineTotal>23</money:LineTotal>
 </OrderedItem>

Remarks

The Serialize method converts the public fields and read/write properties of an object into XML. It does not convert methods, indexers, private fields, or read-only properties.

In the xmlWriter parameter, specify an object that derives from the abstract XmlWriter class. The XmlTextWriter derives from the XmlWriter.

Note

The XmlSerializer cannot serialize the following: arrays of ArrayList and arrays of List<T>.

See also

Applies to

.NET 10 and other versions
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, 10
.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

Serialize(XmlWriter, Object, XmlSerializerNamespaces, String, String)

Source:
XmlSerializer.cs
Source:
XmlSerializer.cs
Source:
XmlSerializer.cs

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

C#
public void Serialize(System.Xml.XmlWriter xmlWriter, object? o, System.Xml.Serialization.XmlSerializerNamespaces? namespaces, string? encodingStyle, string? id);
C#
public void Serialize(System.Xml.XmlWriter xmlWriter, object o, System.Xml.Serialization.XmlSerializerNamespaces namespaces, string encodingStyle, string id);

Parameters

xmlWriter
XmlWriter

The XmlWriter used to write the XML document.

o
Object

The object to serialize.

namespaces
XmlSerializerNamespaces

An instance of the XmlSerializerNamespaces that contains namespaces and prefixes to use.

encodingStyle
String

The encoding used in the document.

id
String

For SOAP encoded messages, the base used to generate id attributes.

Remarks

The id parameter supplies the base string used to create SOAP ids. By default, these are "id1", "id2" and so on. But if the parameter is set to "myBase" the generated values are "myBaseid1", "myBaseid2" and so on. This functionality is used to create unique id values across the whole SOAP message.

Applies to

.NET 10 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 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

Serialize(XmlWriter, Object, XmlSerializerNamespaces, String)

Source:
XmlSerializer.cs
Source:
XmlSerializer.cs
Source:
XmlSerializer.cs

Serializes the specified object and writes the XML document to a file using the specified XmlWriter and references the specified namespaces and encoding style.

C#
public void Serialize(System.Xml.XmlWriter xmlWriter, object? o, System.Xml.Serialization.XmlSerializerNamespaces? namespaces, string? encodingStyle);
C#
public void Serialize(System.Xml.XmlWriter xmlWriter, object o, System.Xml.Serialization.XmlSerializerNamespaces namespaces, string encodingStyle);

Parameters

xmlWriter
XmlWriter

The XmlWriter used to write the XML document.

o
Object

The object to serialize.

namespaces
XmlSerializerNamespaces

The XmlSerializerNamespaces referenced by the object.

encodingStyle
String

The encoding style of the serialized XML.

Exceptions

An error occurred during serialization. The original exception is available using the InnerException property.

Remarks

When the Serialize method is invoked, the public fields and read/write properties of an object are converted into XML. Methods, indexers, private fields, and read-only properties are not serialized.

Use the xmlWriter parameter to specify an object that derives from the abstract XmlWriter class, which is designed to write XML documents. The XmlTextWriter derives from the XmlWriter.

Set the encodingStyle parameter to "http://schemas.xmlsoap.org/soap/encoding/" for SOAP version 1.1 encoding; otherwise, set it to "http://www.w3.org/2001/12/soap-encoding" for SOAP version 1.2 encoding.

Note

The XmlSerializer cannot serialize the following: arrays of ArrayList and arrays of List<T>.

See also

Applies to

.NET 10 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 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

Serialize(XmlWriter, Object, XmlSerializerNamespaces)

Source:
XmlSerializer.cs
Source:
XmlSerializer.cs
Source:
XmlSerializer.cs

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

C#
public void Serialize(System.Xml.XmlWriter xmlWriter, object o, System.Xml.Serialization.XmlSerializerNamespaces namespaces);
C#
public void Serialize(System.Xml.XmlWriter xmlWriter, object? o, System.Xml.Serialization.XmlSerializerNamespaces? namespaces);

Parameters

xmlWriter
XmlWriter

The XmlWriter used to write the XML document.

o
Object

The Object to serialize.

namespaces
XmlSerializerNamespaces

The XmlSerializerNamespaces referenced by the object.

Exceptions

An error occurred during serialization. The original exception is available using the InnerException property.

Examples

The following example serializes an object with an XmlWriter. The example also creates an XmlSerializerNamespaces and adds two namespaces to the object. Several instances of the XmlElementAttribute class are applied to the class members to specify the namespace for each element.

C#
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

// This is the class that will be serialized.
public class OrderedItem5
{
    [XmlElement(Namespace = "http://www.cpandl.com")]
    public string ItemName;
    [XmlElement(Namespace = "http://www.cpandl.com")]
    public string Description;
    [XmlElement(Namespace = "http://www.cohowinery.com")]
    public decimal UnitPrice;
    [XmlElement(Namespace = "http://www.cpandl.com")]
    public int Quantity;
    [XmlElement(Namespace = "http://www.cohowinery.com")]
    public decimal LineTotal;
    // A custom method used to calculate price per item.
    public void Calculate()
    {
        LineTotal = UnitPrice * Quantity;
    }
}

public class Test5
{
    public static void Main()
    {
        Test5 t = new();
        // Write a purchase order.
        t.SerializeObject("simple.xml");
    }

    private void SerializeObject(string filename)
    {
        Console.WriteLine("Writing With XmlTextWriter");

        XmlSerializer serializer = new(typeof(OrderedItem5));
        OrderedItem5 i = new()
        {
            ItemName = "Widget",
            Description = "Regular Widget",
            Quantity = 10,
            UnitPrice = (decimal)2.30
        };
        i.Calculate();

        // Create an XmlSerializerNamespaces object.
        XmlSerializerNamespaces ns = new();

        // Add two namespaces with prefixes.
        ns.Add("inventory", "http://www.cpandl.com");
        ns.Add("money", "http://www.cohowinery.com");

        // Create an XmlTextWriter using a FileStream.
        Stream fs = new FileStream(filename, FileMode.Create);
        XmlTextWriter writer = new(fs, new UTF8Encoding());

        // Serialize using the XmlTextWriter.
        serializer.Serialize(writer, i, ns);
        writer.Close();
    }
}
XML
<?xml version="1.0"?>
 <OrderedItem xmlns:inventory="http://www.cpandl.com" xmlns:money="http://www.cohowinery.com">
   <inventory:ItemName>Widget</inventory:ItemName>
   <inventory:Description>Regular Widget</inventory:Description>
   <money:UnitPrice>2.3</money:UnitPrice>
   <inventory:Quantity>10</inventory:Quantity>
   <money:LineTotal>23</money:LineTotal>
 </OrderedItem>

Remarks

When the Serialize method is invoked, the public fields and read/write properties of an object are converted into XML. Methods, indexers, private fields, and read-only properties are not serialized.

Use the xmlWriter parameter to specify an object that derives from the abstract XmlWriter class, which is designed to write XML documents. The XmlTextWriter derives from the XmlWriter.

Note

The XmlSerializer cannot serialize the following: arrays of ArrayList and arrays of List<T>.

See also

Applies to

.NET 10 and other versions
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, 10
.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

Serialize(TextWriter, Object, XmlSerializerNamespaces)

Source:
XmlSerializer.cs
Source:
XmlSerializer.cs
Source:
XmlSerializer.cs

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

C#
public void Serialize(System.IO.TextWriter textWriter, object o, System.Xml.Serialization.XmlSerializerNamespaces namespaces);
C#
public void Serialize(System.IO.TextWriter textWriter, object? o, System.Xml.Serialization.XmlSerializerNamespaces? namespaces);

Parameters

textWriter
TextWriter

The TextWriter used to write the XML document.

o
Object

The Object to serialize.

namespaces
XmlSerializerNamespaces

The XmlSerializerNamespaces that contains namespaces for the generated XML document.

Exceptions

An error occurred during serialization. The original exception is available using the InnerException property.

Examples

The following example serializes an object with a TextWriter. The example also creates an XmlSerializerNamespaces object and adds two namespaces to the object. The class that defines the serialized object is also attributed with XmlElementAttribute attributes to specify the namespace for each element.

C#
using System;
using System.IO;
using System.Xml.Serialization;

// This is the class that will be serialized.
public class OrderedItem1
{
    [XmlElement(Namespace = "http://www.cpandl.com")]
    public string ItemName;
    [XmlElement(Namespace = "http://www.cpandl.com")]
    public string Description;
    [XmlElement(Namespace = "http://www.cohowinery.com")]
    public decimal UnitPrice;
    [XmlElement(Namespace = "http://www.cpandl.com")]
    public int Quantity;
    [XmlElement(Namespace = "http://www.cohowinery.com")]
    public decimal LineTotal;
    // A custom method used to calculate price per item.
    public void Calculate()
    {
        LineTotal = UnitPrice * Quantity;
    }
}

public class Test1
{
    public static void Main(string[] args)
    {
        Test1 t = new();
        // Write a purchase order.
        t.SerializeObject("simple.xml");
    }

    private void SerializeObject(string filename)
    {
        Console.WriteLine("Writing With TextWriter");
        // Create an XmlSerializer instance using the type.
        XmlSerializer serializer = new(typeof(OrderedItem1));
        OrderedItem1 i = new()
        {
            ItemName = "Widget",
            Description = "Regular Widget",
            Quantity = 10,
            UnitPrice = (decimal)2.30
        };
        i.Calculate();

        // Create an XmlSerializerNamespaces object.
        XmlSerializerNamespaces ns = new();
        // Add two namespaces with prefixes.
        ns.Add("inventory", "http://www.cpandl.com");
        ns.Add("money", "http://www.cohowinery.com");
        // Create a StreamWriter to write with.
        StreamWriter writer = new(filename);
        /* Serialize using the object using the TextWriter
        and namespaces. */
        serializer.Serialize(writer, i, ns);
        writer.Close();
    }
}
XML
<?xml version="1.0"?>
 <OrderedItem xmlns:inventory="http://www.cpandl.com" xmlns:money="http://www.cohowinery.com">
   <inventory:ItemName>Widget</inventory:ItemName>
   <inventory:Description>Regular Widget</inventory:Description>
   <money:UnitPrice>2.3</money:UnitPrice>
   <inventory:Quantity>10</inventory:Quantity>
   <money:LineTotal>23</money:LineTotal>
 </OrderedItem>

Remarks

When the Serialize method is invoked the public fields and read/write properties of an object are converted into XML. Methods, indexers, private fields, and read-only properties are not serialized.

Use the textWriter parameter to specify an object that derives from the abstract TextWriter class. Classes that derive from TextWriter class include:

Note

The XmlSerializer cannot serialize the following: arrays of ArrayList and arrays of List<T>.

See also

Applies to

.NET 10 and other versions
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, 10
.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

Serialize(Object, XmlSerializationWriter)

Source:
XmlSerializer.cs
Source:
XmlSerializer.cs
Source:
XmlSerializer.cs

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

C#
protected virtual void Serialize(object? o, System.Xml.Serialization.XmlSerializationWriter writer);
C#
protected virtual void Serialize(object o, System.Xml.Serialization.XmlSerializationWriter writer);

Parameters

o
Object

The Object to serialize.

writer
XmlSerializationWriter

The XmlSerializationWriter used to write the XML document.

Exceptions

Any attempt is made to access the method when the method is not overridden in a descendant class.

Applies to

.NET 10 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.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

Serialize(TextWriter, Object)

Source:
XmlSerializer.cs
Source:
XmlSerializer.cs
Source:
XmlSerializer.cs

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

C#
public void Serialize(System.IO.TextWriter textWriter, object o);
C#
public void Serialize(System.IO.TextWriter textWriter, object? o);

Parameters

textWriter
TextWriter

The TextWriter used to write the XML document.

o
Object

The Object to serialize.

Examples

The following example serializes an object using a TextWriter.

C#
using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;

// This is the class that will be serialized.
public class OrderedItem
{
    public string ItemName;
    public string Description;
    public decimal UnitPrice;
    public int Quantity;
    public decimal LineTotal;
    // A custom method used to calculate price per item.
    public void Calculate()
    {
        LineTotal = UnitPrice * Quantity;
    }
}

public class Test
{
    public static void Main(string[] args)
    {
        Test t = new();
        // Write a purchase order.
        t.SerializeObject("simple.xml");
    }

    private void SerializeObject(string filename)
    {
        Console.WriteLine("Writing With TextWriter");

        XmlSerializer serializer = new(typeof(OrderedItem));
        OrderedItem i = new()
        {
            ItemName = "Widget",
            Description = "Regular Widget",
            Quantity = 10,
            UnitPrice = (decimal)2.30
        };
        i.Calculate();

        /* Create a StreamWriter to write with. First create a FileStream
           object, and create the StreamWriter specifying an Encoding to use. */
        FileStream fs = new(filename, FileMode.Create);
        StreamWriter writer = new(fs, new UTF8Encoding());
        // Serialize using the XmlTextWriter.
        serializer.Serialize(writer, i);
        writer.Close();
    }
}
XML
<?xml version="1.0"?>
 <OrderedItem xmlns:inventory="http://www.cpandl.com" xmlns:money="http://www.cohowinery.com">
   <inventory:ItemName>Widget</inventory:ItemName>
   <inventory:Description>Regular Widget</inventory:Description>
   <money:UnitPrice>2.3</money:UnitPrice>
   <inventory:Quantity>10</inventory:Quantity>
   <money:LineTotal>23</money:LineTotal>
 </OrderedItem>

Remarks

The Serialize method converts the public fields and read/write properties of an object into XML. It does not convert methods, indexers, private fields, or read-only properties.

In the textWriter parameter, specify an object that derives from the abstract TextWriter class. Classes that derive from TextWriter include:

Note

The XmlSerializer cannot serialize the following: arrays of ArrayList and arrays of List<T>.

See also

Applies to

.NET 10 and other versions
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, 10
.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

Serialize(Stream, Object)

Source:
XmlSerializer.cs
Source:
XmlSerializer.cs
Source:
XmlSerializer.cs

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

C#
public void Serialize(System.IO.Stream stream, object o);
C#
public void Serialize(System.IO.Stream stream, object? o);

Parameters

stream
Stream

The Stream used to write the XML document.

o
Object

The Object to serialize.

Exceptions

An error occurred during serialization. The original exception is available using the InnerException property.

Examples

The following example serializes an object using a Stream object.

C#
using System;
using System.IO;
using System.Xml.Serialization;

// This is the class that will be serialized.
public class OrderedItem2
{
    public string ItemName;
    public string Description;
    public decimal UnitPrice;
    public int Quantity;
    public decimal LineTotal;

    // A custom method used to calculate price per item.
    public void Calculate()
    {
        LineTotal = UnitPrice * Quantity;
    }
}

public class Test2
{
    public static void Main(string[] args)
    {
        Test2 t = new();
        // Write a purchase order.
        t.SerializeObject("simple.xml");
    }

    private void SerializeObject(string filename)
    {
        Console.WriteLine("Writing With Stream");

        XmlSerializer serializer = new(typeof(OrderedItem2));
        OrderedItem2 i = new()
        {
            ItemName = "Widget",
            Description = "Regular Widget",
            Quantity = 10,
            UnitPrice = (decimal)2.30
        };
        i.Calculate();

        // Create a FileStream to write with.
        FileStream writer = new(filename, FileMode.Create);
        // Serialize the object, and close the TextWriter
        serializer.Serialize(writer, i);
        writer.Close();
    }
}
XML
<?xml version="1.0"?>
 <OrderedItem xmlns:inventory="http://www.cpandl.com" xmlns:money="http://www.cohowinery.com">
   <inventory:ItemName>Widget</inventory:ItemName>
   <inventory:Description>Regular Widget</inventory:Description>
   <money:UnitPrice>2.3</money:UnitPrice>
   <inventory:Quantity>10</inventory:Quantity>
   <money:LineTotal>23</money:LineTotal>
 </OrderedItem>

Remarks

The Serialize method converts the public fields and read/write properties of an object into XML. It does not convert methods, indexers, private fields, or read-only properties.

In the stream parameter, specify an object that derives from the abstract Stream class. Classes that derive from Stream include:

Note

The XmlSerializer cannot serialize the following: arrays of ArrayList and arrays of List<T>.

See also

Applies to

.NET 10 and other versions
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, 10
.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

Serialize(Stream, Object, XmlSerializerNamespaces)

Source:
XmlSerializer.cs
Source:
XmlSerializer.cs
Source:
XmlSerializer.cs

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

C#
public void Serialize(System.IO.Stream stream, object o, System.Xml.Serialization.XmlSerializerNamespaces namespaces);
C#
public void Serialize(System.IO.Stream stream, object? o, System.Xml.Serialization.XmlSerializerNamespaces? namespaces);

Parameters

stream
Stream

The Stream used to write the XML document.

o
Object

The Object to serialize.

namespaces
XmlSerializerNamespaces

The XmlSerializerNamespaces referenced by the object.

Exceptions

An error occurred during serialization. The original exception is available using the InnerException property.

Examples

The following example serializes an object with a Stream object. The example also creates an XmlSerializerNamespaces and adds two namespaces to the object. The class that defines the serialized object is also attributed with XmlElementAttribute attributes to specify the namespace for each element.

C#
using System;
using System.IO;
using System.Xml.Serialization;

// This is the class that will be serialized.
public class OrderedItem3
{
    [XmlElement(Namespace = "http://www.cpandl.com")]
    public string ItemName;
    [XmlElement(Namespace = "http://www.cpandl.com")]
    public string Description;
    [XmlElement(Namespace = "http://www.cohowinery.com")]
    public decimal UnitPrice;
    [XmlElement(Namespace = "http://www.cpandl.com")]
    public int Quantity;
    [XmlElement(Namespace = "http://www.cohowinery.com")]
    public decimal LineTotal;

    // A custom method used to calculate price per item.
    public void Calculate()
    {
        LineTotal = UnitPrice * Quantity;
    }
}

public class Test3
{
    public static void Main()
    {
        Test3 t = new();
        // Write a purchase order.
        t.SerializeObject("simple.xml");
        t.DeserializeObject("simple.xml");
    }

    private void SerializeObject(string filename)
    {
        Console.WriteLine("Writing With Stream");

        XmlSerializer serializer =
            new(typeof(OrderedItem3));

        OrderedItem3 i = new()
        {
            ItemName = "Widget",
            Description = "Regular Widget",
            Quantity = 10,
            UnitPrice = (decimal)2.30
        };
        i.Calculate();

        // Create an XmlSerializerNamespaces object.
        XmlSerializerNamespaces ns = new();

        // Add two prefix-namespace pairs.
        ns.Add("inventory", "http://www.cpandl.com");
        ns.Add("money", "http://www.cohowinery.com");

        // Create a FileStream to write with.
        FileStream writer = new(filename, FileMode.Create);

        // Serialize the object, and close the TextWriter
        serializer.Serialize(writer, i, ns);
        writer.Close();
    }

    private void DeserializeObject(string filename)
    {
        Console.WriteLine("Reading with Stream");
        // Create an instance of the XmlSerializer.
        XmlSerializer serializer = new(typeof(OrderedItem3));

        // Writing the file requires a Stream.
        Stream reader = new FileStream(filename, FileMode.Open);

        // Declare an object variable of the type to be deserialized.
        OrderedItem3 i;

        /* Use the Deserialize method to restore the object's state
           using data from the XML document. */
        i = (OrderedItem3)serializer.Deserialize(reader);

        // Write out the properties of the object.
        Console.Write(
            i.ItemName + "\t" +
            i.Description + "\t" +
            i.UnitPrice + "\t" +
            i.Quantity + "\t" +
            i.LineTotal);
    }
}

Remarks

When the Serialize method is invoked, the public fields and read/write properties of an object are converted into XML. Methods, indexers, private fields, and read-only properties are not serialized.

Use the stream parameter to specify an object that derives from the abstract Stream class, which is designed to write to streams. Classes that derive from the Stream class include:

Note

The XmlSerializer cannot serialize the following: arrays of ArrayList and arrays of List<T>.

See also

Applies to

.NET 10 and other versions
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, 10
.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