Home
Blog
Contact
Mailing List
Software
Blog
Twitter
|
<< 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"?>
<People>
<Person>
<Name>Tom Hearn</Name>
<Birthday>1983-05-18 04:16:24</Birthday>
<Contact>
<Twitter>nerdyhearn</Twitter>
</Contact>
</Person>
</People>
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
).First(),
};
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) {
MessageBox.Show(person.Name);
...
}
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.
Tags
CSharp
XML
Related Blogs
Creating an MD5 String Extension method in C#
Bitmasking userAccountControl attribute in LDAP from C#
Comparing XML files in C# Using Microsoft's Diff and Patch Tool
Comments
Currently no comments.
Add A Comment
Name:
URL:
Email Address: (not public, used to send notifications on further comments)
Comments:

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