Saturday, December 15, 2007

Annotation on XObject from LINQ to XML

Annotation is something like tag or helper object on XML node. You could register multiple annotations. It is registered under signature of method which was used for registration. So when you are registering some classes with common interface, cast the registered instance to the interface first!
To get annotation of value type you will need to use typeof() as parameter.
interface IHandler { void Handle(XElement e);}
class CatHandler : IHandler
{
    public void Handle(XElement e) 
    { Console.WriteLine(e.Attribute("Food").Value); }
}
class DogHandler : IHandler
{
    public void Handle(XElement e) 
    { Console.WriteLine(e.Element("Friend").Value); }
}

class Test
{
static void Main(string[] args)
{
    List<XElement> list=new List<XElement>()
    {
        new XElement("Creature", 
            new XElement("Name", "Bijou"), 
            new XAttribute("Food", "milk"),
            new XAttribute("Type", "Cat")),
        new XElement("Creature", 
            new XElement("Name", "Goro"),
            new XElement("Friend", "Reiko"),
            new XAttribute("Type", "Dog"))
    };

    //registration
    foreach (XElement element in list)
    {
        switch(element.Attribute("Type").Value)
        {
        case "Cat" : 
            element.AddAnnotation((IHandler)new CatHandler());
            break;
        case "Dog" : 
            element.AddAnnotation((IHandler)new DogHandler());
            break;
        }
    }

    //usage
    foreach (XElement element in list)
    {
        element.Annotation<IHandler>().Handle(element);
    }
}
}

No comments: