Home   |   QuickStart Welcome   |   ASP.NET   |   Web Services   |   How Do I...?   
  |   I want my samples in...      

How Do I...? Common Tasks QuickStart Tutorial

How do I read/write objects into xml?

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.

  1. First, you will 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 are almost there. Use the XSD.exe tool to create these classes automatically. You can also build the classes manually. You can find more information on how to do this in the "How do I Create an XSD schema from a class?" topic.

    This example will 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.

    VB PurchaseOrder.vb
    View Source
    [This sample can be found at C:\DevFusion.Data\legacy\quickstart.developerfusion.co.uk\QuickStart\howto\samples\Xmlserialization\]
    PurchaseOrder.XSD
    View Source
    [This sample can be found at C:\DevFusion.Data\legacy\quickstart.developerfusion.co.uk\QuickStart\howto\samples\Xmlserialization\]

  2. 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.

    XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder));
  3. To read the file, call the Deserialize method passing in a Stream, TextReader, or XmlReader. A purchase order will be returned.

    		
    TextReader reader = new StreamReader("po.xml");
    PurchaseOrder po = (PurchaseOrder)serializer.Deserialize(reader);
    reader.Close();
    
    C#

  4. To write the file, call the Serialize method passing in a Stream, TextReader, or XmlReader as well as an instance of the purchase order.

    		
    TextWriter writer = new StreamWriter("po2.xml");
    serializer.Serialize(writer, po);
    writer.Close();
    
    C#
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.

VB ReadWriteXML
View Source
PurchaseOrder.xml
View Source



Microsoft .NET Framework SDK QuickStart Tutorials Version 2.0
Copyright � 2004 Microsoft Corporation. All rights reserved.