Merging XML using Visual Basic 9

I made some modifications to my Visual Studio Tip of the Day browser application I created last week. There I am downloading the RSS feed from Sara’s blog and saving it to disk so that I only retrieve the next tip every 24 hours. However, the RSS only returns the last 15 posts so instead of completely replacing the cached feed on disk I want to merge the old tips from the cache file into the downloaded rss feed so that the older tips are preserved. This is really easy using a LINQ to XML query. 

If My.Settings.CacheFile = “” Then

            My.Settings.CacheFile = _

       Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & “\tiprss.xml”

End If

 

Dim file = My.Computer.FileSystem.GetFileInfo(My.Settings.CacheFile)

‘Only load from the web once per day, else load from the cache

If Not file.Exists OrElse file.LastWriteTime.Date < Now.Date Then

 

      Me.Feed = XDocument.Load(My.Settings.TipsURI)

 

      If file.Exists Then

          ‘Put the old items from the cache into the new feed.

          Dim cache = XDocument.Load(My.Settings.CacheFile)

 

          Dim oldItems = From cacheItem In cache…<item> _

                         Group Join item In Me.Feed…<item> _

                             On cacheItem.<guid>.Value Equals item.<guid>.Value _

                             Into Count() _

                         Where Count = 0 _

                         Select cacheItem

 

          Dim items = Me.Feed…<item>

          Dim lastitem = items(items.Count – 1)

          lastitem.AddAfterSelf(oldItems)

      End If

 

      Me.Feed.Save(My.Settings.CacheFile)

Else

      Me.Feed = XDocument.Load(My.Settings.CacheFile)

End If

Notice that all I’m doing here is selecting the old tips from the cache feed by using a group join to the new feed where the count of items in the group is 0. This is similar to the syntax NOT IN(subquery) in T-Sql. This will return any items in the cache feed that do not already exist in the new feed. (I also updated the location of the cache based on community feedback so it would be Vista friendly.) I updated the sample here.

Enjoy!