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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

)

)

);

}

}

}

The indentation gives you an overall visualization of the document structure.

To save the XML document to file, use the Save()method:

library.Save("Books.xml");

To print out the XML document as a string, use the ToString()method:

Console.WriteLine(library.ToString());

When printed, the XML document looks like this:

Wrox

Wrox

O'Reilly

Apress

O'Reilly

To load an XML document into the XDocument object, use the Load()method:

XDocument LibraryBooks = new XDocument();

LibraryBooks = XDocument.Load("Books.xml");

Querying Elements

You can use LINQ to XML to locate specific elements. For example, to retrieve all books published by Wrox, you can use the following query:

var query1 =

from book in LibraryBooks.Descendants("Book")

where book.Element("Publisher").Value == "Wrox"

select book.Element("Title").Value;

Console.WriteLine("------");

Console.WriteLine("Result");

Console.WriteLine("------");

foreach (var book in query1) {

Console.WriteLine(book);

}

This query generates the following output:

------

Result

------

C# 2008 Programmers' Reference

Professional Windows Vista Gadgets Programming

To retrieve all not-yet-published (NYP) books from Wrox, you can use the following query:

var query2 =

from book in library.Descendants("Book")

where book.Attribute("published").Value == "NYP" &&

book.Element("Publisher").Value=="Wrox"

select book.Element("Title").Value;

You can shape the result of a query as you've seen in earlier sections:

var query3 =

from book in library.Descendants("Book")

where book.Element("Publisher").Value == "Wrox"

select new {

Name = book.Element("Title").Value,

Pub = book.Element("Publisher").Value

};

Console.WriteLine("------");

Console.WriteLine("Result");

Console.WriteLine("------");

foreach (var book in query3) {

Console.WriteLine("{0} ({1})", book.Name, book.Pub);

}

This code generates the following output:

------

Result

------

C# 2008 Programmers' Reference (Wrox)

Professional Windows Vista Gadgets Programming (Wrox)

Besides using an anonymous type to reshape the result, you can also pass the result to a non-anonymous type. For example, suppose that you have the following class definition:

public class Book {

public string Name { get; set; }

public string Pub { get; set; }

}

You can shape the result of a query to the Bookclass, as the following example shows:

var query4 =

from book in library.Descendants("Book")

where book.Element("Publisher").Value == "Wrox"

select new Book {

Name = book.Element("Title").Value,

Pub = book.Element("Publisher").Value

};

List books = query4.ToList();

An Example Using RSS

Let's now take a look at the usefulness of LINQ to XML. Suppose that you want to build an application that downloads an RSS document, extracts the title of each posting, and displays the link to each post.

Figure 14-13 shows an example of an RSS document.

Figure 1413 To load an XML document directly from the Internet you can use - фото 202

Figure 14-13

To load an XML document directly from the Internet, you can use the Load() method from the XDocumentclass:

XDocument rss =

XDocument.Load(@"http://www.wrox.com/WileyCDA/feed/RSS_WROX_ALLNEW.xml");

To retrieve the title of each posting and then reshape the result, use the following query:

var posts =

from item in rss.Descendants("item")

select new {

Title = item.Element("title").Value,

URL = item.Element("link").Value

};

In particular, you are looking for all the elements and then for each element found you would extract the values of the and

elements.

...

...

...

...

...

Finally, print out the title and URL for each post:

foreach (var post in posts) {

Console.WriteLine("{0}", post.Title);

Console.WriteLine("{0}", post.URL);

Console.WriteLine();

}

Figure 14-14 shows the output.

Figure 1414 Query Elements with a Namespace If you observe the RSS - фото 203

Figure 14-14

Query Elements with a Namespace

If you observe the RSS document structure carefully, you notice that the element has the dcnamespace defined (see Figure 14-15).

Figure 1415 The dcnamespace is defined at the top of the document within - фото 204

Figure 14-15

The dcnamespace is defined at the top of the document, within the element (see Figure 14-16).

Figure 1416 When using LINQ to XML to query elements defined with a - фото 205

Figure 14-16

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

Интервал:

Закладка:

Сделать

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

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


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

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

x