Generating an XML Tree with a LINQ Query
using System; using System.Linq; using System.Xml.Linq; using System.Collections.Generic; class Program/*w ww . ja v a 2 s . c o m*/ { static void Main(string[] args){ Book[] Books = new[] { new Book {FirstName = "Joe", LastName = "Ruby", ParticipantType = ParticipantTypes.Author}, new Book {FirstName = "PHP", LastName = "Python", ParticipantType = ParticipantTypes.Editor} }; XElement xBooks = new XElement("Books", Books.Select(p => new XElement("Book", new XAttribute("type", p.ParticipantType), new XElement("FirstName", p.FirstName), new XElement("LastName", p.LastName)))); Console.WriteLine(xBooks); } } enum ParticipantTypes { Author = 0, Editor } class Book { public string FirstName; public string LastName; public ParticipantTypes ParticipantType; }
The following code creates an array of Book objects named Books.
Next, the code queries the values from the Books array using the Select operator and generates a Book element for each, using the members of the element of the array.