Export (0) Print
Expand All

XmlSerializer.Serialize Method (Stream, Object, XmlSerializerNamespaces)

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

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

public void Serialize(
	Stream stream,
	Object o,
	XmlSerializerNamespaces namespaces
)

Parameters

stream
Type: System.IO.Stream

The Stream used to write the XML document.

o
Type: System.Object

The Object to serialize.

namespaces
Type: System.Xml.Serialization.XmlSerializerNamespaces

The XmlSerializerNamespaces referenced by the object.

ExceptionCondition
InvalidOperationException

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

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

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:

NoteNote:

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

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.

using System;
using System.IO;
using System.Xml.Serialization;

// This is the class that will be serialized. 
public class OrderedItem {
    [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 Test {

   public static void Main() {
        Test t = new Test();
        // 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 XmlSerializer(typeof(OrderedItem));

        OrderedItem i = new OrderedItem();
        i.ItemName = "Widget";
        i.Description = "Regular Widget";
        i.Quantity = 10;
        i.UnitPrice = (decimal) 2.30;
        i.Calculate();

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

        // 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.
        Stream writer = new FileStream(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 XmlSerializer(typeof(OrderedItem));

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

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

        /* Use the Deserialize method to restore the object's state 
           using data from the XML document. */
        i = (OrderedItem) 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);
    }
}
#using <mscorlib.dll>
#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 __gc class OrderedItem {
public:
   [XmlElement(Namespace = S"http://www.cpandl.com")]
   String* ItemName;
   [XmlElement(Namespace = S"http://www.cpandl.com")]
   String* Description;
   [XmlElement(Namespace=S"http://www.cohowinery.com")]
   Decimal UnitPrice;
   [XmlElement(Namespace = S"http://www.cpandl.com")]
   int Quantity;
   [XmlElement(Namespace=S"http://www.cohowinery.com")]
   Decimal LineTotal;

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

void SerializeObject(String* filename) {
   Console::WriteLine(S"Writing With Stream");

   XmlSerializer* serializer = 
      new XmlSerializer(__typeof(OrderedItem));

   OrderedItem* i = new OrderedItem();
   i->ItemName = S"Widget";
   i->Description = S"Regular Widget";
   i->Quantity = 10;
   i->UnitPrice = (Decimal) 2.30;
   i->Calculate();

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

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

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

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

void DeserializeObject(String* filename) {
   Console::WriteLine(S"Reading with Stream");
   // Create an instance of the XmlSerializer.
   XmlSerializer* serializer = new XmlSerializer(__typeof(OrderedItem));

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

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

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

   // Write out the properties of the object.
   Console::Write(S"{0}\t{1}\t{2}\t{3}\t{4}",
      i->ItemName, i->Description, __box(i->UnitPrice), __box(i->Quantity), i->LineTotal);
}

int main() {
   // Write a purchase order.
   SerializeObject(S"simple.xml");
   DeserializeObject(S"simple.xml");
}

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

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

.NET Framework

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

.NET Compact Framework

Supported in: 3.5, 2.0

XNA Framework

Supported in: 3.0, 2.0, 1.0

Community Additions

ADD
Show:
© 2014 Microsoft