Mailing List



NerdyHearn - Blog

<< Back To All Blogs

Reading an XML file using LINQ

Saturday, January 10th, 2009

Over the past couple of days I have been playing with LINQ. I have put this off for I don't know how many months since it was first released and now I am wishing that I started using it months ago. Think of LINQ as an SQL query for programming. That is the most basic and simple explanation and it has thus far made my life working with XML incredibly easy. No more XML parsers and XPath for me, strictly LINQ!

I think the best way to display what I mean is to just jump strait into some code. Please note the introduction of the new variable type "var" keyword in C#. This allows for dynamic casting for all of the objects returned through each query.

For the sake of our example, we will be using an XML snippet such as the following:

<?xml version="1.0"?>
<Name>Tom Hearn</Name>
<Birthday>1983-05-18 04:16:24</Birthday>

To select from this you would use the following LINQ query:

XDocument logXml = XDocument.Parse(input);

var people = from person in logXml.Descendants("Person")
select new Person
Name = person.Element("Name").Value,
Birthday = DateTime.Parse(person.Element("Birthday").Value),
Twitter = (
from contact in person.Descendants("Contact")
select contact.Value

The simple structure that we would have defined in order to select into the type would be as follows:

public class Person {
public string Name { get; set; }
public DateTime Birthday { get; set; }
public string Twitter { get; set; }

You can then enumerate the returned types as:
foreach (var person in people) {

Please also note 2 important things in the LINQ query above:
1) You can easily type-cast directly inside the query such as in the example of the Birthday setter
2) Sub-queries can be infinitely nested to select further into the XML document, which is very useful!

LINQ is no small topic, and I have a bunch more to learn, but thought I'd go ahead and share on my way to learning it completely!

LINQin' Tom Out.


CSharp XML

Related Blogs

Updating an LDAP Property in C#
SharePoint Web Services, .NET 3.5, and Authentication Issues
Retrieving Text from Win32 SDK's GetLastError() in C#
Reading A Database Schema in SQLite with C#
Bitmasking userAccountControl attribute in LDAP from C#


Currently no comments.

Add A Comment



Email Address: (not public, used to send notifications on further comments)


Enter the text above, except for the 1st and last character:

NerdyHearn - Latest tech news relating to C#, ASP.NET, SharePoint, PHP, general development, and more. SaveMySerials - Protect yourself from theft, fire, natural disasters and more by recording your serial numbers