Deserializing XML


After an extensive look at the serialization process, next take a look at how you can reverse this process and deserialize an XML document back into a usable object in your code. For this, you use the same XmlSerializer object, but instead of using the Serialize method, you make use of the object's Deserialize method.

For an example of using the Deserialize method, you first establish a serialized object in a flat file. Listing 15-9 shows the MyXML.xml file that you need for this example.

Listing 15-9: The MyXML.xml file

image from book
      <?xml version="1.0" encoding="utf-8"?>      <MultiStockOrder>        <StockOrderMultiple>         <StockOrder>            <Symbol>MSFT</Symbol>            <Quantity>100</Quantity>            <OrderTime>2005-10-04</OrderTime>         </StockOrder>         <StockOrder>            <Symbol>INTC</Symbol>            <Quantity>110</Quantity>            <OrderTime>2005-10-04</OrderTime>         </StockOrder>           <StockOrder>            <Symbol>RTRSY</Symbol>            <Quantity>200</Quantity>            <OrderTime>2005-10-04</OrderTime>          </StockOrder>         </StockOrderMultiple>      </MultiStockOrder> 
image from book

Instead of an XML file with just a single stock order in an XML file, this XML file has an array of orders (3), which will all be deserialized and placed into an array of your customized type, StockOrder. Next, you create a new class that contains an array of StockOrder objects in your console application. This class, MultiStockOrder.cs, is displayed in Listing 15-10.

Listing 15-10: A class representing an array of StockOrder objects

image from book
      using System;      using System.Collections.Generic;      using System.Text;      namespace XmlSerializationProject      {          public class MultiStockOrder          {              public StockOrder[] StockOrderMultiple;          }      } 
image from book

This class and the previous StockOrder.cs class define the syntax that your XML document from Listing 15-9 takes. Figure 15-6 illustrates just this.

image from book
Figure 15-6

Next, deserializing this into a usable object is rather simple in .NET. Listing 15-11 shows how the MultiStockOrder object is deserialized from a file on disk, MyXML.xml and how the file's contents are used.

Listing 15-11: The deserialization of XML to the MultiStockOrder object

image from book
            using System;      using System.Collections.Generic;      using System.Text;      using System.Xml;      using System.Xml.Serialization;      using System.IO;      namespace XmlSerializationProject      {          class Program          {              static void Main(string[] args)              {                  try                  {                     FileStream dehydrated = new                        FileStream("C:/MyXML.xml", FileMode.Open);                     XmlSerializer serialize = new                        XmlSerializer(typeof(MultiStockOrder));                     MultiStockOrder myOrder = new MultiStockOrder();                     myOrder = (MultiStockOrder) serialize.Deserialize(dehydrated);                     foreach(StockOrder singleOrder in myOrder.StockOrderMultiple)                     {                        Console.WriteLine("{0}, {1}, {2}",                           singleOrder.Symbol,                           singleOrder.Quantity,                           singleOrder.OrderTime.ToShortDateString());                     }                     dehydrated.Close();                     Console.ReadLine();                  }                  catch (System.Exception ex)                  {                     Console.Error.WriteLine(ex.ToString());                     Console.ReadLine();                  }              }          }      } 
image from book

The Deserialize method takes a few constructions. Some of them include the following:

      Deserialize(Stream)      Deserialize(TextReader)      Deserialize(XmlReader) 

From this list, you can see that the Deserialize method takes a couple of possible inputs. The first, is a stream, and from the code Listing 15-11, you can determine this is what is being used (a FileStream object). Other possibilities include a TextReader object, or even an XmlReader object, which you look at shortly.

In Listing 15-11, first the FileStream object is used to pull the data from the MyXML.xml file. Then, as before, the XmlSerializer object is instantiated, but this time it is cast as a new object type-MultiStockOrder. From there, an instance of the MultiStockOrder is created and populated through the deserialization of the XmlSerializer.

      myOrder = (MultiStockOrder) serialize.Deserialize(dehydrated); 

At this point, the MultiStockOrder instance (myOrder) contains everything that was stored in the MyXML.xml file. Now the job is to iterate through each of the single orders contained in the class instance. This is done by using a foreach statement where each of the values for each order is output to the console. In the end, the console application produces the results illustrated in Figure 15-7.

image from book
Figure 15-7

From this example, you can see that it is quite easy to serialize objects to XML and then deserialize that XML back into a usable object.




Professional XML
Professional XML (Programmer to Programmer)
ISBN: 0471777773
EAN: 2147483647
Year: 2004
Pages: 215

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net