This topic describes how to automatically map a particular xml stream into a set of objects designed to hold the XML using the XML Serialization classes.<p>
<ol>
<li>First, you'll need classes designed to work with the XML Serialization classes. If you have an XSD schema that describes the format of the XML file you want to load or save, you're almost there. <a href="XsdToCls.aspx">Use the XSD.exe tool</a> to create these classes automatically. You can also build the classes by hand. Some information on how to do this can be found in the <a href="XsdFromCls.aspx">"How do I Create an XSD schema from a class?"</a> topic. <p>
For this example, we'll be using the PurchaseOrder classes that were generated to read XML in the format defined by the purchase order schema. Both the classes and the schema are shown below.<p>
<li>Create an instance of the XmlSerializer, passing the type of the object you would like to deserialize. Here we will use the PurchaseOrder type that was defined earlier.<p>
<div class="code"><xmp>
XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder));
</xmp></div>
<li>To read the file, call the Deserialize method passing in a Stream, TextReader, or XmlReader. A purchase order will be returned.
<div class="code"><xmp>
TextReader reader = new StreamReader("po.xml");
PurchaseOrder po = (PurchaseOrder)serializer.Deserialize(reader);
reader.Close();
</xmp></div>
<li>To write the file, call the Serialize method passing in a Stream, TextReader, or XmlReader as well as an instance of the purchase order.
<div class="code"><xmp>
TextWriter writer = new StreamWriter("po2.xml");
serializer.Serialize(writer, po);
writer.Close();
</xmp></div>
</ol>
The following example puts these ideas together by reading the purchase order XML file shown below, and then writing it back out to another file.<p>