15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

938 ❘ ChaPTer 33 mAnipulAtinG xml<br />

Product newPd;<br />

//new filestream to open serialized object<br />

FileStream f = new FileStream("serialprod.xml", FileMode.Open);<br />

Once again, you create a new XmlSerializer, passing in the type information of Product. You can then<br />

make the call to the Deserialize() method. Note that you still need to do an explicit cast when you create<br />

the newPd object. At this point, newPd is in exactly the same state that pd was:<br />

//new serializer<br />

XmlSerializer newSr = new XmlSerializer(typeof(Product));<br />

//deserialize the object<br />

newPd = (Product)newSr.Deserialize(f);<br />

f.Close();<br />

MessageBox.Show(newPd.ToString());<br />

}<br />

code snippet frmSerial.cs<br />

The message box should show you the product ID, product name, <strong>and</strong> the unit price of the object you just<br />

deserialized. This comes from the ToString() override that you implemented in the Product class.<br />

What about situations where you have derived classes <strong>and</strong> possibly properties that return an array<br />

XmlSerializer has that covered as well. Here’s a slightly more complex example that deals with these issues.<br />

First, you define three new classes, Product, BookProduct (derived from Product), <strong>and</strong> Inventory (which<br />

contains both of the other classes). Notice that once again you have overridden the ToString() method.<br />

This time you’re just going to list the items in the Inventory class:<br />

public class BookProduct: Product<br />

{<br />

private string isbnNum;<br />

public BookProduct() {}<br />

public string ISBN<br />

{<br />

get {return isbnNum;}<br />

set {isbnNum=value;}<br />

}<br />

}<br />

public class Inventory<br />

{<br />

private Product[] stuff;<br />

public Inventory() {}<br />

//need to have an attribute entry for each data type<br />

[XmlArrayItem("Prod",typeof(Product)),<br />

XmlArrayItem("Book",typeof(BookProduct))]<br />

public Product[] InventoryItems<br />

{<br />

get {return stuff;}<br />

set {stuff=value;}<br />

}<br />

public override string ToString()<br />

{<br />

StringBuilder outText = new StringBuilder();<br />

foreach (Product prod in stuff)<br />

{<br />

outText.Append(prod.ProductName);<br />

outText.Append("\r\n");<br />

}<br />

return outText.ToString();<br />

}<br />

}<br />

code snippet frmSerial.cs<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!