Wei-Meng Lee - C# 2008 Programmer's Reference

Здесь есть возможность читать онлайн «Wei-Meng Lee - C# 2008 Programmer's Reference» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Indianapolis, Год выпуска: 2009, ISBN: 2009, Издательство: Wiley Publishing, Inc., Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

C# 2008 Programmer's Reference: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «C# 2008 Programmer's Reference»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

C# 2008 Programmers Reference provides a concise and thorough reference on all aspects of the language. Each chapter contains detailed code samples that provide a quick and easy way to understand the key concepts covered.

C# 2008 Programmer's Reference — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «C# 2008 Programmer's Reference», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

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.Serializationnamespace.

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

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 1115 As you can see the object is serialized into an XML document with - фото 178

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 Cityinformation is not persisted in the XML document (nor as the Line2in the second Addresselement) 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 currentAgeproperty 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;

} finally {

xr.Close();

}

return obj;

}

Here, you can use the XmlReaderclass's Create()method to open an XML file for reading.

The XmlReaderclass is used to read the data from the XML file. The deserialized object is then returned to the calling function.

Remember to import the System.Xmlnamespace for the XmlReaderclass.

To test the XMLDeserialize()function, call it directly after an object has been serialized, 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);

Member m2 = XMLDeserialize(@"c:\Members.xml");

Console.WriteLine("{0}, {1}", m2.Name.FirstName, m2.Name.LastName);

Console.WriteLine("{0}", m2.currentAge);

foreach (MemberAddress a in m2.Addresses) {

Console.WriteLine("{0}", a.Line1);

Console.WriteLine("{0}", a.Line2);

Console.WriteLine("{0}", a.Country);

Console.WriteLine("{0}", a.Postal);

Console.WriteLine();

}

Console.ReadLine();

}

The output of these statements is shown in Figure 11-16.

Figure 1116 Customizing the Serialization Process Despite the fairly automated - фото 179

Figure 11-16

Customizing the Serialization Process

Despite the fairly automated task performed by the XMLSerializer object, you can customize the way the XML document is generated. Here's an example of how you can modify classes with a few attributes:

[XmlRoot("MemberInformation",

Namespace = "http://www.learn2develop.net",

IsNullable = true)]

public class Member {

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «C# 2008 Programmer's Reference»

Представляем Вашему вниманию похожие книги на «C# 2008 Programmer's Reference» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «C# 2008 Programmer's Reference»

Обсуждение, отзывы о книге «C# 2008 Programmer's Reference» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x