Create Tag-Cloud from RSS Feed in ASP.NET MVC

Say you want to generate your own tag-cloud from a list of categories or tags you pull from an RSS-feed or similar. This is one way to do it. I’m using ASP.NET MVC for this sample which creates a simple tag-cloud in a Razor-view with HTML looking something like this:

image

The controller-code to start out with looks like this, where you read in the RSS-feed into a SyndicationFeed class, then pull out and flatten all the categories you have in that feed. Then group all those categories and count them to build up this simple view-model which is a Dictionary of category and percentage:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        //get feed
        var feed = SyndicationFeed.Load(XmlReader.Create("http://blog.irm.se/blogs/MainFeed.aspx"));

        //get flat list of all categories/tags in the feed
        var categoriesList = feed.Items.SelectMany(item => item.Categories).Select(category => category.Name);

        var categoryGroups = categoriesList.GroupBy(category => category);

        decimal maxNrOfACategory = categoryGroups.Max(w => w.Count());

        //build a dictionary with category/percentage of all categories
        var tagCloudDictionary = new Dictionary<string, int>();
        foreach (var tag in categoryGroups)
        {
            var percent = (tag.Count() / maxNrOfACategory) * 100;
            tagCloudDictionary.Add(tag.Key, (int)percent);
        }

        return View(tagCloudDictionary);
    }
}

 

So now we got this view-model which is a Dictionary<string,int> and contains category/percentage data like this:

image

So all we need to do is create some kind of cloud in HTML or similar in the view. One way of doing it is this, which creates the output shown at the top:

@model Dictionary<string, int>

@{
    ViewBag.Title = "Index";
}

<h2>Tag cloud</h2>
<div style="width: 400px; font-size: 25px;">
    @foreach (var tag in Model)
    {
        <span style="font-size: @(tag.Value / 2 + 50)%; ">
        @if (tag.Value > 10)
        {
            <span style=" font-weight: bold;">@tag.Key </span>
        }
        else
        {
            <span>@tag.Key </span>
        }
        </span>
    }
</div>

 

Obviously, to be able to click on a tag and so on you need to create a richer view-model, I just wanted to show how I grab and count the tags from the feed Smile

No Comments