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!
Beth is a Program Manager on the Visual Studio Community Team at Microsoft and is responsible for producing and managing content for business application developers, driving community features and team participation onto MSDN Developer Centers (http://msdn.com), and helping make Visual Studio one of the best developer tools in the world. She also produces regular content on her blog (http://blogs.msdn.com/bethmassi), Channel 9, and a variety of other developer sites and magazines. As a community champion and a long-time member of the Microsoft developer community she also helps with the San Francisco East Bay .NET user group and is a frequent speaker at various software development events. Before Microsoft, she was a Senior Architect at a health care software product company and a Microsoft Solutions Architect MVP. Over the last decade she has worked on distributed applications and frameworks, web and Windows-based applications using Microsoft development tools in a variety of businesses. She loves teaching, hiking, mountain biking, and driving really fast.