Using LINQ to query against objects and XML by ThinqLinq

Using LINQ to query against objects and XML

In preparing for my LINQ talk for DBA's at tomorrow's Atlanta Microsoft Database Forum user group meeting, I thought it would be good to offer a quick look at the LINQ to Objects and LINQ to XML stacks before focusing on the OR mapping portions: LINQ to SQL,  LINQ to Entities and LINQ to dataSet. I previously used a quick demo which joined  the FileInfo collection returned by DirectoryInfo.GetFiles with an object collection built from a CSV file. For this demo, I wanted to add in the XML stack. Making this change is a relatively minor task.

First, I converted the CSV file to a simple XML document. See my previous post to see how straight-forward the conversion is. Once converted, our XML looks like the following:

<FileTypes>
   <FileType extension=".doc" description="Microsoft Word Document" />
   <FileType extension=".log" description="Log File" />
   <FileType extension=".msg" description="Mail Message" />
   <FileType extension=".rtf" description="Rich Text Format" />
   <FileType extension=".txt" description="Text File" />
   <FileType extension=".wpd" description="WordPerfect Document" />
</FileTypes>

To query this, we need to first load the XML document. LINQ to XML offers a single line method to load a XML document using the simple "Load" method.

Dim FileTypes As XDocument = XDocument.Load("C:\FileTypes.xml")

Once we have the document, we can easily get a collection of elements using the .Descendents("FileType") method. VB 9 offers a more concise method which retains a more type safe mechanism. Here we identify the specific nodes we want to access (FileTypes.<FileTypes>.<FileType>). With this collection in hand, we can replace the old CSV based collection with the new XML collection using the following LINQ query.

Dim results = _
From fi In New DirectoryInfo("C:\Windows").GetFiles, _
ext In FileTypes.<FileTypes>.<FileType> _
Where fi.LastAccessTime >= Now.AddDays(-6) _
And fi.Extension = ext.Attribute("extension").Value _
Select New {FileName := fi.Name, lastAccess := fi.LastAccessTime, Exten := ext.Attribute("description").Value} _
Order By FileName Descending

Posted on - Comment
Categories: LINQ - Linq to XML -
comments powered by Disqus