2005-04-12 Dick Porter <dick@ximian.com>
[mono.git] / mcs / class / System.XML / System.Xml.Serialization / standalone_tests / potest.cs
1 using System;
2 using System.Xml;
3 using System.Xml.Serialization;
4 using System.IO;
5
6 // The XmlRootAttribute allows you to set an alterate name
7 // (PurchaseOrder) for the XML element and its namespace. By
8 // default, the XmlSerializer uses the class name. The attribute
9 // also allows you to set the XML namespace for the element. Lastly,
10 // the attribute sets the IsNullable property, which specifies whether
11 // the xsi:null attribute appears if the class instance is set to
12 // a null reference.
13 [XmlRootAttribute("PurchaseOrder", Namespace="http://cpandl.com",
14                   IsNullable=false)]
15 public class PurchaseOrder
16 {
17         public Address ShipTo;
18         public string OrderDate;
19         // The XmlArrayAttribute changes the XML element name
20         // from the default of "OrderedItems" to "Items".
21         [XmlArrayAttribute("Items")]
22         public OrderedItem[] OrderedItems;
23         public decimal SubTotal;
24         public decimal ShipCost;
25         public decimal TotalCost;
26 }
27
28 public class Address
29 {
30         // The XmlAttribute instructs the XmlSerializer to serialize the Name
31         // field as an XML attribute instead of an XML element (the default
32         // behaviour).
33         [XmlAttribute]
34         public string Name;
35         public string Line1;
36
37         // Setting the IsNullable property to false instructs the
38         // XmlSerializer that the XML attribute will not appear if
39         // the City field is set to a null reference.
40         [XmlElementAttribute(IsNullable=false)]
41         public string City;
42         public string State;
43         public string Zip;
44 }
45
46 public class OrderedItem
47 {
48         public string ItemName;
49         public string Description;
50         public decimal UnitPrice;
51         public int Quantity;
52         public decimal LineTotal;
53
54         // Calculate is a custom method that calculates the price per item
55         // and stores the value in a field.
56         public void Calculate()
57         {
58                 LineTotal=UnitPrice*Quantity;
59         }
60 }
61
62 public class Test
63 {
64         public static void Main()
65         {
66                 // Read and write purchase orders.
67                 Test t=new Test();
68                 t.CreatePO("potest.xml");
69                 t.ReadPO("potest.xml");
70         }
71
72         private void CreatePO(string filename)
73         {
74                 // Creates an instance of the XmlSerializer class;
75                 // specifies the type of object to serialize.
76                 XmlSerializer serializer=new XmlSerializer(typeof(PurchaseOrder));
77                 TextWriter writer=new StreamWriter(filename);
78                 PurchaseOrder po=new PurchaseOrder();
79
80                 // Creates an address to ship and bill to.
81                 Address billAddress=new Address();
82                 billAddress.Name="Teresa Atkinson";
83                 billAddress.Line1="1 Main St.";
84                 billAddress.City="AnyTown";
85                 billAddress.State="WA";
86                 billAddress.Zip="00000";
87                 // Sets ShipTo and BillTo to the same addressee.
88                 po.ShipTo=billAddress;
89                 po.OrderDate=System.DateTime.Now.ToLongDateString();
90
91                 // Creates an OrderedItem.
92                 OrderedItem i1=new OrderedItem();
93                 i1.ItemName="Widget S";
94                 i1.Description="Small widget";
95                 i1.UnitPrice=(decimal)5.23;
96                 i1.Quantity=3;
97                 i1.Calculate();
98
99                 // Inserts the item into the array.
100                 OrderedItem[] items={i1};
101                 po.OrderedItems=items;
102                 // Calculate the total cost.
103                 decimal subTotal=new decimal();
104                 foreach(OrderedItem oi in items)
105                 {
106                         subTotal+=oi.LineTotal;
107                 }
108                 po.SubTotal=subTotal;
109                 po.ShipCost=(decimal)12.51;
110                 po.TotalCost=po.SubTotal+po.ShipCost;
111                 // Serializes the purchase order, and closes the TextWriter.
112                 serializer.Serialize(writer, po);
113                 writer.Close();
114         }
115
116         protected void ReadPO(string filename)
117         {
118                 // Creates an instance of the XmlSerializer class;
119                 // specifies the type of object to be deserialized.
120                 XmlSerializer serializer=new XmlSerializer(typeof(PurchaseOrder));
121                 // If the XML document has been altered with unknown
122                 // nodes or attributes, handles them with the
123                 // UnknownNode and UnknownAttribute events.
124                 serializer.UnknownNode+=new XmlNodeEventHandler(serializer_UnknownNode);
125                 serializer.UnknownAttribute+=new XmlAttributeEventHandler(serializer_UnknownAttribute);
126
127                 // A FileStream is needed to read the XML document.
128                 FileStream fs=new FileStream(filename, FileMode.Open);
129                 // Declares an object variable of the type to be deserialized.
130                 PurchaseOrder po;
131                 // Uses the Deserialize method to restore the object's state with
132                 // data from the XML document. */
133                 po=(PurchaseOrder)serializer.Deserialize(fs);
134                 fs.Close();
135                 
136                 // Reads the order date.
137                 Console.WriteLine("OrderDate: "+po.OrderDate);
138
139                 // Reads the shipping address.
140                 Address shipTo=po.ShipTo;
141                 ReadAddress(shipTo, "Ship To:");
142                 // Reads the list of ordered items.
143                 OrderedItem[] items=po.OrderedItems;
144                 Console.WriteLine("Items to be shipped:");
145                 foreach(OrderedItem oi in items)
146                 {
147                         Console.WriteLine("\t"+
148                                           oi.ItemName+"\t"+
149                                           oi.Description+"\t"+
150                                           oi.UnitPrice+"\t"+
151                                           oi.Quantity+"\t"+
152                                           oi.LineTotal);
153                 }
154                 // Reads the subtotal, shipping cost, and total cost.
155                 Console.WriteLine("\n\t\t\t\t\t Subtotal\t"+po.SubTotal+
156                                   "\n\t\t\t\t\t Shipping\t"+po.ShipCost+
157                                   "\n\t\t\t\t\t Total\t\t"+po.TotalCost);
158         }
159
160         protected void ReadAddress(Address a, string label)
161         {
162                 // Reads the fields of the Address.
163                 Console.WriteLine(label);
164                 Console.Write("\t"+
165                               a.Name+"\n\t"+
166                               a.Line1+"\n\t"+
167                               a.City+"\t"+
168                               a.State+"\n\t"+
169                               a.Zip+"\n");
170         }
171
172         protected void serializer_UnknownNode(object sender,
173                                               XmlNodeEventArgs e)
174         {
175                 Console.WriteLine("Unknown Node:"+e.Name+"\t"+e.Text);
176         }
177
178         protected void serializer_UnknownAttribute(object sender,
179                                                    XmlAttributeEventArgs e)
180         {
181                 System.Xml.XmlAttribute attr=e.Attr;
182                 Console.WriteLine("Unknown attribute "+attr.Name+"='"+attr.Value+"'");
183         }
184 }