CSharp - Add annotations based on their type attribute

Description

Add annotations based on their type attribute

Demo

using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;

class Program//w  ww. j  ava  2 s. 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);
            }
        }
    }
}

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"));
    }
}

Result

Related Topic