![]()
Serialize Dataset
1
private void SerializeDataSet(string filename)
{
2
XmlSerializer ser = new XmlSerializer(typeof(DataSet));
3
4
// Creates a DataSet; adds a table, column, and ten rows.
5
DataSet ds = new DataSet("myDataSet");
6
DataTable t = new DataTable("table1");
7
DataColumn c = new DataColumn("thing");
8
t.Columns.Add(c);
9
ds.Tables.Add(t);
10
DataRow r;
11
for(int i = 0; i<10;i++)
{
12
r = t.NewRow();
13
r[0] = "Thing " + i;
14
t.Rows.Add(r);
15
}
16
TextWriter writer = new StreamWriter(filename);
17
ser.Serialize(writer, ds);
18
writer.Close();
19
}
1

private void SerializeElement(string filename)
{2
XmlSerializer ser = new XmlSerializer(typeof(XmlElement));3
XmlElement myElement= 4
new XmlDocument().CreateElement("MyElement", "ns");5
myElement.InnerText = "Hello World";6
TextWriter writer = new StreamWriter(filename);7
ser.Serialize(writer, myElement);8
writer.Close();9
}10

11

private void SerializeNode(string filename)
{12
XmlSerializer ser = new XmlSerializer(typeof(XmlNode));13
XmlNode myNode= new XmlDocument().14
CreateNode(XmlNodeType.Element, "MyNode", "ns");15
myNode.InnerText = "Hello Node";16
TextWriter writer = new StreamWriter(filename);17
ser.Serialize(writer, myNode);18
writer.Close();19
}1
MySerializableClass myObject = new MySerializableClass();2
// Insert code to set properties and fields of the object.3
XmlSerializer mySerializer = new 4
XmlSerializer(typeof(MySerializableClass));5
// To write to a file, create a StreamWriter object.6
StreamWriter myWriter = new StreamWriter("myFileName.xml");7
mySerializer.Serialize(myWriter, myObject);8
myWriter.Close();1
MySerializableClass myObject;2
// Construct an instance of the XmlSerializer with the type3
// of object that is being deserialized.4
XmlSerializer mySerializer = 5
new XmlSerializer(typeof(MySerializableClass));6
// To read the file, create a FileStream.7
FileStream myFileStream = 8
new FileStream("myFileName.xml", FileMode.Open);9
// Call the Deserialize method and cast to the object type.10
myObject = (MySerializableClass) 11
mySerializer.Deserialize(myFileStream)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 alternate 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://www.cpandl.com",14
IsNullable = false)]15
public class PurchaseOrder16


{17
public Address ShipTo;18
public string OrderDate;19
// The XmlArrayAttribute changes the XML element name20
// 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 Address29


{30
// The XmlAttribute instructs the XmlSerializer to serialize the 31
// Name field as an XML attribute instead of an XML element (the 32
// default behavior).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 OrderedItem47


{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 item55
// and stores the value in a field.56
public void Calculate()57

{58
LineTotal = UnitPrice * Quantity;59
}60
}61

62
public class Test63


{64
public static void Main()65

{66
// Read and write purchase orders.67
Test t = new Test();68
t.CreatePO("po.xml");69
t.ReadPO("po.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 =77
new XmlSerializer(typeof(PurchaseOrder));78
TextWriter writer = new StreamWriter(filename);79
PurchaseOrder po = new PurchaseOrder();80

81
// Creates an address to ship and bill to.82
Address billAddress = new Address();83
billAddress.Name = "Teresa Atkinson";84
billAddress.Line1 = "1 Main St.";85
billAddress.City = "AnyTown";86
billAddress.State = "WA";87
billAddress.Zip = "00000";88
// Sets ShipTo and BillTo to the same addressee.89
po.ShipTo = billAddress;90
po.OrderDate = System.DateTime.Now.ToLongDateString();91

92
// Creates an OrderedItem.93
OrderedItem i1 = new OrderedItem();94
i1.ItemName = "Widget S";95
i1.Description = "Small widget";96
i1.UnitPrice = (decimal)5.23;97
i1.Quantity = 3;98
i1.Calculate();99

100
// Inserts the item into the array.101

OrderedItem[] items =
{ i1 };102
po.OrderedItems = items;103
// Calculate the total cost.104
decimal subTotal = new decimal();105
foreach (OrderedItem oi in items)106

{107
subTotal += oi.LineTotal;108
}109
po.SubTotal = subTotal;110
po.ShipCost = (decimal)12.51;111
po.TotalCost = po.SubTotal + po.ShipCost;112
// Serializes the purchase order, and closes the TextWriter.113
serializer.Serialize(writer, po);114
writer.Close();115
}116

117
protected void ReadPO(string filename)118

{119
// Creates an instance of the XmlSerializer class;120
// specifies the type of object to be deserialized.121
XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder));122
// If the XML document has been altered with unknown 123
// nodes or attributes, handles them with the 124
// UnknownNode and UnknownAttribute events.125
serializer.UnknownNode += new126
XmlNodeEventHandler(serializer_UnknownNode);127
serializer.UnknownAttribute += new128
XmlAttributeEventHandler(serializer_UnknownAttribute);129

130
// A FileStream is needed to read the XML document.131
FileStream fs = new FileStream(filename, FileMode.Open);132
// Declares an object variable of the type to be deserialized.133
PurchaseOrder po;134
// Uses the Deserialize method to restore the object's state 135
// with data from the XML document. */136
po = (PurchaseOrder)serializer.Deserialize(fs);137
// Reads the order date.138
Console.WriteLine("OrderDate: " + po.OrderDate);139

140
// Reads the shipping address.141
Address shipTo = po.ShipTo;142
ReadAddress(shipTo, "Ship To:");143
// Reads the list of ordered items.144
OrderedItem[] items = po.OrderedItems;145
Console.WriteLine("Items to be shipped:");146
foreach (OrderedItem oi in items)147

{148
Console.WriteLine("\t" +149
oi.ItemName + "\t" +150
oi.Description + "\t" +151
oi.UnitPrice + "\t" +152
oi.Quantity + "\t" +153
oi.LineTotal);154
}155
// Reads the subtotal, shipping cost, and total cost.156
Console.WriteLine(157
"\n\t\t\t\t\t Subtotal\t" + po.SubTotal +158
"\n\t\t\t\t\t Shipping\t" + po.ShipCost +159
"\n\t\t\t\t\t Total\t\t" + po.TotalCost160
);161
}162

163
protected void ReadAddress(Address a, string label)164

{165
// Reads the fields of the Address.166
Console.WriteLine(label);167
Console.Write("\t" +168
a.Name + "\n\t" +169
a.Line1 + "\n\t" +170
a.City + "\t" +171
a.State + "\n\t" +172
a.Zip + "\n");173
}174

175
protected void serializer_UnknownNode176
(object sender, XmlNodeEventArgs e)177

{178
Console.WriteLine("Unknown Node:" + e.Name + "\t" + e.Text);179
}180

181
protected void serializer_UnknownAttribute182
(object sender, XmlAttributeEventArgs e)183

{184
System.Xml.XmlAttribute attr = e.Attr;185
Console.WriteLine("Unknown attribute " +186
attr.Name + "='" + attr.Value + "'");187
}188
}1
<?xml version="1.0" encoding="utf-8"?>2
<PurchaseOrder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.cpandl.com">3
<ShipTo Name="Teresa Atkinson">4
<Line1>1 Main St.</Line1>5
<City>AnyTown</City>6
<State>WA</State>7
<Zip>00000</Zip>8
</ShipTo>9
<OrderDate>Wednesday, June 27, 2001</OrderDate>10
<Items>11
<OrderedItem>12
<ItemName>Widget S</ItemName>13
<Description>Small widget</Description>14
<UnitPrice>5.23</UnitPrice>15
<Quantity>3</Quantity>16
<LineTotal>15.69</LineTotal>17
</OrderedItem>18
</Items>19
<SubTotal>15.69</SubTotal>20
<ShipCost>12.51</ShipCost>21
<TotalCost>28.2</TotalCost>22
</PurchaseOrder>原创地址:http://www.cnblogs.com/shark2076/archive/2007/04/07/703875.html
浙公网安备 33010602011771号