XMLSerializer class from the System.Xml.Serialization namespace:

static void Main(string[] args) {}

//========XML Serialization=========

static void XMLSerialize(Member mem) {

 StreamWriter sw = new StreamWriter(@'c: Members.xml');

 try {

  XmlSerializer s = new XmlSerializer(typeof(Member));

  s.Serialize(sw, mem);

 } catch (Exception ex) {

  Console.WriteLine(ex.ToString());

 } finally {

  sw.Close();

 }

}

For XML serialization, you need to import the System.Xml.Serialization namespace.

In the XMLSerialize() function, you first create a new StreamWriter object so that you can save the serialized XML string to a file. The Serialize() method from the XMLSerializer class serializes the Member object into an XML string, which is then written to file by using the StreamWriter class.

To test the XMLSerialize() function, assume that you have the following object declarations:

static void Main(string[] args) {

 MemberAddress address1 = new MemberAddress() {

  Line1 = 'One Way Street',

  Line2 = 'Infinite Loop',

  Country = 'SINGAPORE',

  Postal = '456123'

 };

 MemberAddress address2 = new MemberAddress() {

  Line1 = 'Two Way Street',

  Country = 'SINGAPORE',

  Postal = '456123'

 };

 Member m1 = new Member() {

  Name = new MemberName() {

   FirstName = 'Wei-Meng', LastName = 'Lee'

  },

  DOB = Convert.ToDateTime(@'5/1/1972'),

  Addresses = new MemberAddress[] { address1, address2 }

 };

}

To serialize the Member object, invoke the XMLSerialize() method like this:

static void Main(string[] args) {

 MemberAddress address1 = new MemberAddress() {

  Line1 = 'One Way Street',

  Line2 = 'Infinite Loop',

  Country = 'SINGAPORE',

  Postal = '456123'

 };

 MemberAddress address2 = new MemberAddress() {

  Line1= 'Two Way Street',

  Country = 'SINGAPORE',

  Postal = '456123'

 };

 Member m1 = new Member() {

  Name = new MemberName() {

   FirstName = 'Wei-Meng',

   LastName = 'Lee'

  },

  DOB = Convert.ToDateTime(@'5/1/1972'),

  Addresses = new MemberAddress[] { address1, address2 }

 };

 XMLSerialize(m1);

}

Figure 11-15 shows the XML document generated by the XMLSerialize() function.

Figure 11-15

As you can see, the object is serialized into an XML document with a format corresponding to the structure of the object. Here are some important points to note:

□ The City information is not persisted in the XML document (nor as the Line2 in the second Address element) because it was not assigned in the objects. You will see later how to persist empty elements, even though a value is not assigned.

□ All read/write properties in the object are persisted in the XML document, except the read-only currentAge property in the Member class.

□ Only public variables are persisted; private variables are not persisted in XML serialization.

□ The default name for each element in the XML document is drawn from the variable (or class) name. In most cases this is desirable, but sometimes the element names might not be obvious.

Deserializing the Class

To deserialize the XML document, simply use the Deserialize() method from the XMLSerializer class. Define the XMLDeserialize() function as follows:

static void Main(string[] args) {

 //...

}

//========XML Serialization=========

static Member XMLDeserialize(string xmlFile) {

 Member obj;

 XmlReader xr = XmlReader.Create(xmlFile);

 try {

  XmlSerializer s = new XmlSerializer(typeof(Member));

  obj = (Member)s.Deserialize(xr);

 } catch (Exception ex) {

  Console.WriteLine(ex.ToString());

  obj = null;

Вы читаете C# 2008 Programmer's Reference
Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

Вы можете отметить интересные вам фрагменты текста, которые будут доступны по уникальной ссылке в адресной строке браузера.

Отметить Добавить цитату