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" ?>

<contacts>

  <contact>

    <name age="28">Wriju</name>

    <email>wriju@abc.com</email>

  </contact>

  <contact>

    <name age="25">Tupur</name>

    <email>tups@abc.com</email>

  </contact>

</contacts>

 

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

while(reader.Read())

{

   

    switch(reader.NodeType)

    {

        case XmlNodeType.Element:

            if(reader.Name=="name")

                strOutput += "\r\nname:";

            if(reader.Name=="email")

                strOutput += "\r\nemail:";

            break;

        case XmlNodeType.Text:

                strOutput += reader.Value;

            break;

    }

}

 

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.

 

Namoskar