I Think I Love LINQ

I am beggining to really like to ease of using LINQ, On a project I am working on now I am storing configuration in an XML file like so:

<sites>
    <site id="1" sitename="foo">
       <domains>
          <domain url="www.foo.com" />
       </domains>
       <settings>
          <setting key="foo" value="foo" />
       </settings>
    </site>
</sites>

My original solution to load this involded looping over the nodes looping over the domains and settings and loading this into my Site object. Time consuming to write and looked messy. And then LINQ to XML steps in. My code to parse this XML file into my collection of Site objects now becomes:

Me.Sites = (From site In document.Descendants("site") _
                        Select New Site With { _
                        .ID = site.Attribute("id").Value, _
                        .SiteName = site.Attribute("sitename").Value, _
                        .Domains = (From domain In site.Elements("domains").Descendants("domain") _
                                    Select domain) _
                                    .ToDictionary(Function(domain) domain.Attribute("url").Value, Function(domain) domain.Attribute("url").Value), _
                        .Settings = (From setting In site.Elements("settings").Descendants("setting") _
                                    Select setting) _
                                    .ToDictionary(Function(setting) setting.Attribute("key").Value, Function(setting) setting.Attribute("value").Value) _
                        }).ToList()



The speed of this is actually pretty fast and I tested with some large XML files and was happy with the performance. And I dont think life can get easier....


Cheers

Stefan
 

No Comments