XmlSerializer::Serialize Method (Stream^, Object^)


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

Namespace:   System.Xml.Serialization
Assembly:  System.Xml (in System.Xml.dll)

void Serialize(
	Stream^ stream,
	Object^ o


Type: System.IO::Stream^

The Stream used to write the XML document.

Type: System::Object^

The Object to serialize.

Exception Condition

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

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. To serialize all of an object's fields and properties, both public and private, use the BinaryFormatter.

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


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

The following example serializes an object using a Stream object.

#using <System.Xml.dll>
#using <System.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml::Serialization;

// This is the class that will be serialized.
public ref class OrderedItem
   String^ ItemName;
   String^ Description;
   Decimal UnitPrice;
   int Quantity;
   Decimal LineTotal;

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

void SerializeObject( String^ filename )
   Console::WriteLine( "Writing With Stream" );
   XmlSerializer^ serializer = gcnew XmlSerializer( OrderedItem::typeid );
   OrderedItem^ i = gcnew OrderedItem;
   i->ItemName = "Widget";
   i->Description = "Regular Widget";
   i->Quantity = 10;
   i->UnitPrice = (Decimal)2.30;

   // Create a FileStream to write with.
   Stream^ writer = gcnew FileStream( filename,FileMode::Create );

   // Serialize the object, and close the TextWriter
   serializer->Serialize( writer, i );

int main()
   // Write a purchase order.
   SerializeObject( "simple.xml" );
<?xml version="1.0"?>
 <OrderedItem xmlns:inventory="http://www.cpandl.com" xmlns:money="http://www.cohowinery.com">
   <inventory:Description>Regular Widget</inventory:Description>

Universal Windows Platform
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top