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" ?>
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";
strOutput += "\r\nname:";
strOutput += "\r\nemail:";
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;
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.
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();
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.
Nice piece of code. Thanks for pointing it out.
You are correct. Thanks again.