Linq and Extension methods

I wanted to read a blob of xml and then display some attribute and few elements as HTML. With the help of Linq and extension method, the code can be very clean and simple.

The xml I want to read looks like as follows:

  <W S="Arrogate">
    <M>To claim or demand unduly.</M>
    <S> accroach, appropriate, assume </S>
    <A> appropriate, give, hand over </A>
    <E>The teenager arrogated that he must get pocket money.</E>

Here is the code to convert this XML into HTML in a very nice manner

 static void Main(string[] args)
            string FileName = AppDomain.CurrentDomain.BaseDirectory + "Lesson1.xml";
            var doc = XElement.Load(FileName);
            var query = from ele in doc.Elements(@"W")
                        select ele;
            foreach (var v in query)
               Console.WriteLine(v.ToHTMLReady ());

The function ToHTMLReady() is the function which does all the magic. However, there is no ‘ToHTMLReady’ function defined on XElement, so where does this come from? This is one of the beauty of extension method. This function is defined as follows:

public static class MyExtensionMethod  
  public static string ToHTMLReady(this XElement  ele)
            return "<B>WORD: </B>" + (string)ele.Attribute("S") + " <B> Example: </B>" + ele.Element("E").Value;

using this extension method concept you can do all the heavy lifting manuplating XML, while keeping the main code very clean and simple.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s