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

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215
