Enumerate through the elements and retrieve the element's annotation:
using System; using System.Linq; using System.Xml.Linq; using System.Collections.Generic; class Program//from w w w .j a v a 2s . co m { static void Main(string[] args) { // we will use this to store a reference to one of the elements in the XML tree. XElement firstParticipant; XDocument xDocument = new XDocument( new XElement("Books", firstParticipant = new XElement("Book", new XAttribute("type", "Author"), new XAttribute("experience", "first-time"), new XAttribute("language", "English"), new XElement("FirstName", "Joe"), new XElement("LastName", "Ruby")), new XElement("Book", new XAttribute("type", "Editor"), new XElement("FirstName", "PHP"), new XElement("LastName", "Python")))); // Display the document for reference. Console.WriteLine(xDocument + System.Environment.NewLine); // we'll add some annotations based on their type attribute. foreach (XElement e in xDocument.Element("Books").Elements()) { if ((string)e.Attribute("type") == "Author") { AuthorHandler aHandler = new AuthorHandler(); e.AddAnnotation(aHandler); } else if ((string)e.Attribute("type") == "Editor") { EditorHandler eHandler = new EditorHandler(); e.AddAnnotation(eHandler); } } AuthorHandler aHandler2; EditorHandler eHandler2; foreach (XElement e in xDocument.Element("Books").Elements()) { if ((string)e.Attribute("type") == "Author") { aHandler2 = e.Annotation<AuthorHandler>(); if (aHandler2 != null) { aHandler2.Display(e); } } else if ((string)e.Attribute("type") == "Editor") { eHandler2 = e.Annotation<EditorHandler>(); if (eHandler2 != null) { eHandler2.Display(e); } } } } } public class AuthorHandler { public void Display(XElement element) { Console.WriteLine("AUTHOR BIO"); Console.WriteLine("Name: {0} {1}", (string)element.Element("FirstName"), (string)element.Element("LastName")); Console.WriteLine("Language: {0}", (string)element.Attribute("language")); Console.WriteLine("Experience: {0}", (string)element.Attribute("experience")); } } public class EditorHandler { public void Display(XElement element) { Console.WriteLine("EDITOR BIO"); Console.WriteLine("Name: {0}", (string)element.Element("FirstName")); Console.WriteLine(" {0}", (string)element.Element("LastName")); } }