Wriju's BLOG

.NET, Cloud and everything

XLinq : System.Xml.XLinq vs System.Xml


System.Xml has given the communication power to dot net and XLinq has refined that. It was very nice experience we have explored how to read XML using . NET. Now we are more excited to see how easily we can get the required value with less code (which was one of the philosophies behind the LINQ Project). Let us have an example on that.


Assume this is your XML


<?xml version=1.0 encoding=utf-8 ?>



    <name age=28>Wriju</name>




    <name age=25>Tupur</name>





To read the Name and Email element in traditional .NET way you need to write this code (may be not standard but more or less solves the purpose)


string strOutput = “”;

XmlTextReader reader = new XmlTextReader(@”..\..\Contacts.xml”);

strOutput += “\r\n”;






        case XmlNodeType.Element:


                strOutput += “\r\nname:”;       


                strOutput += “\r\nemail:”; 


        case XmlNodeType.Text:

                strOutput += reader.Value;        





The same can be achieved through XLinq (using the namespace System.Xml.XLinq)


var doc = XDocument.Load(@”..\..\Contacts.xml”);

var items = doc.Element(“contacts”).Elements(“contact”);

foreach(var item in items)


    strOutput += “\r\n” +

item.Element(“name”).Name + “:” + item.Element(“name”).Value;

    strOutput += “\r\n” +

item.Element(“email”).Name + “:” + item.Element(“email”).Value;



Less code and more powerful, I am now exploring the XLinq query and it awesome. I will write on that in my next blog.