Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_for_Beginners.doc
Скачиваний:
35
Добавлен:
13.02.2015
Размер:
2.39 Mб
Скачать

Compiling the Code

Copy the code and paste it into the Main method of a console application. Replace "c:\\IntroToVCS.xml" with the actual file name.

Note:

The XML document must be well-formed.

Robust Programming

The following condition(s) may cause an exception:

  • The path name may be too long.

Чтение xml из файла

Этот пример использует класс XmlTextReader для извлечения названий элементов и текстовых строк из файла образца и сохранения данных в строковой переменной.

Пример18

System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("c:\\IntroToVCS.xml");

string contents = "";

while (reader.Read())

{

reader.MoveToContent();

if (reader.NodeType == System.Xml.XmlNodeType.Element)

contents += "<"+reader.Name + ">\n";

if (reader.NodeType == System.Xml.XmlNodeType.Text)

contents += reader.Value + "\n";

}

System.Console.Write(contents);

Компиляция кода

Скопируйте код и вставьте его в метод Main консольного приложения.

Замените "c:\\IntroToVCS.xml" фактическим именем файла.

Примечание.

Документ XML должен быть правильно сформированным.

Надежное программирование

Исключение может возникнуть при следующих условиях.

  • Имя пути имеет слишком большую длину.

How to: Read Class Data from an xml File

This example uses the Deserialize method of the XmlSerializerclass to read data that is stored in an object in a sample file that is named IntroToVCS.xml.

Example

public class Book

{

public string title;

static void Main()

{

Book introToVCS = new Book();

System.Xml.Serialization.XmlSerializer reader = new

System.Xml.Serialization.XmlSerializer(introToVCS.GetType());

// Read the XML file.

System.IO.StreamReader file=

new System.IO.StreamReader("c:\\IntroToVCS.xml");

// Deserialize the content of the file into a Book object.

introToVCS = (Book) reader.Deserialize(file);

System.Windows.Forms.MessageBox.Show(introToVCS.title,

"Book Title");

}

}

Compiling the Code

You can compile the example directly at a command prompt, or paste the code into a console application by using the Visual Studio IDE. In the latter case, you must reference the System.Windows.Forms.dll file.

Robust Programming

The following condition(s) may cause an exception:

  • The path name may be too long.

Чтение данных класса из xml-файла

В этом примере для чтения данных, хранящихся в объекте в образце файла с именем IntroToVCS.xml, используется метод Deserialize класса XmlSerializer.

Пример19

public class Book

{

public string title;

static void Main()

{

Book introToVCS = new Book();

System.Xml.Serialization.XmlSerializer reader = new

System.Xml.Serialization.XmlSerializer(introToVCS.GetType());

// Read the XML file.

System.IO.StreamReader file=

new System.IO.StreamReader("c:\\IntroToVCS.xml");

// Deserialize the content of the file into a Book object.

introToVCS = (Book) reader.Deserialize(file);

System.Windows.Forms.MessageBox.Show(introToVCS.title, "Book Title");

}

}

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]