Populating XML elements tree with Linq

I find Linq to comes in handy from time-to-time, especially when I refactor my code and try to shorten it. Consider this example, let’s say I have a Book data that I want to dump into XML document. Now I have a Book class to represent the object.

    class Book
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public string Author { get; set; }
        public double Price { get; set; }
        public Book(int id, string title, string author, double price)
        {
            ID = id;
            Title = title;
            Author = author;
            Price = price;
        }
    }

To dump a collection of Book to XML, the old fashion way of doing it is creating foreach loop over Book collection and create XML object. With Linq it can become a one-liner.

            List<book> bookList = new List<book>();
 
            //Create book collection
            bookList.Add(new Book
                            (787, @"The Back of the Napkin: "+
                             @"Solving Problems and Selling "+
                             @"Ideas with Pictures", "Dan Roam", 16.47));
            bookList.Add(new Book
                (89, @"Presentation Zen: Simple Ideas "+
                 @"on Presentation Design and Delivery"
                 , "Garr Reynolds", 19.79));
            bookList.Add(new Book
                (897, @"C# in Depth: What you need to master C# 2 and 3",
                "Jon Skeet", 26.29));
 
            //Generate XML tree from Book collection data
            XElement xmlElement =
                        new XElement("Books",
                                bookList.Select(
                                    book => new XElement("Book",
                                                new XAttribute("ID", book.ID.ToString()),
                                                new XElement("Title", book.Title),
                                                new XElement("Author", book.Author),
                                                new XElement("Price", book.Price)
                                                        )
                                               )
                                    );
            Console.WriteLine("{0}", xmlElement.ToString());</book></book>

This query yields the XML output. No loop or messy enumeration required, the code is also more readable the Linq query.

Teera on August 4th 2008 in Software Development, Web Dev, .NET

Trackback URI | Comments RSS

Leave a Reply