How to generate XML from data source in C#

Let’s Web developer has to develop a page where the user submits a file containing the ISBN of all the books he/she needs information about. The user has to retrieve these books and create an XML file with the book title, author and price.

Web developer can use a LINQ query to pass child elements and nest data, by exploiting a possibility to pass a list of elements to the XElement constructor. The following C# code lines show this approach:

var books = BooksFromAQuery();
var book =
   new XDocument(
   new XElement(“Books”,
      from b in books
      select new XElement(“Book”,
         new XElement(“ISBN”, b.ISBN),
         new XElement(“Title”, b.Title),
         new XElement(“Author”, b.Author),
         new XElement(“Price”, b.Price
      )
   )
);