Книга: C# 2008 Programmer
Querying Elements
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 Book
class, 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<Book> books = query4.ToList();