XLinq : System.Xml.XLinq vs System.Xml

XLinq : System.Xml.XLinq vs System.Xml

  • Comments 2

 

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

 

Leave a Comment
  • Please add 7 and 8 and type the answer here:
  • Post
  • I agree that Xlinq is very nice, however to be fair, you could do the job much similer with system.xml as well:

    XmlDocument doc = new XmlDocument();

    doc.Load("@"..\..\Contacts.xml");

    foreach(XmlElement e in doc.DocumentsElement["Contacts"])

    strOut += "\r\nName:" + e["name"].InnerText + "\r\nemail:" + e["email"].InnerText;

    There are other examples, that Xlinq can really do things better than System.xml.

  • Hi Yuval,

    Nice piece of code. Thanks for pointing it out.

    You are correct. Thanks again.

    Wriju

Page 1 of 1 (2 items)