So I started learning XLinq last evening and I thought I would try to parse a samle RSS document like found at http://weblogs.asp.net/scottgu/rss.aspx
My test was to find all entries which fit the following criteria
a) Was Posted in the year 2008 b) Had atleast one comment c) Had the tag ".NET"
So I am wondering if my solution(though it works) would be considered a "good solution". XLinq gurus please weight in. Code below
XDocument document = XDocument.Load(fileName);
XNamespace dcNamespace = "http://purl.org/dc/elements/1.1/";
XNamespace slashNamespace = "http://purl.org/rss/1.0/modules/slash/";
var items = from item in document.Descendants("item")
where Convert.ToDateTime(item.Element("pubDate").Value).Year == 2008 &&
Convert.ToInt32(item.Element(slashNamespace + "comments").Value) > 0
select new
{
Title = item.Element("title").Value,
Link = item.Element("link").Value,
PublishedDate = Convert.ToDateTime(item.Element("pubDate").Value),
comments = Convert.ToInt32(item.Element(slashNamespace + "comments").Value),
Tags = (from category in item.Elements("category")
where !string.IsNullOrEmpty(category.Value)
orderby category.Value
select category).ToList()
};
const string requiredTag = ".NET";
var dotNetTaggedItems = from item in items
where item.Tags.Any(x => x.Value == requiredTag)
select item;
if (items.Any(item => item.PublishedDate.Year != 2008)) //Check that the year is valid
throw new InvalidOperationException("Invalid PublishedDate");
int totalComments = 0;
foreach (var taggedItem in dotNetTaggedItems)
{
if (taggedItem.comments > 0) //Check that the comments are valid
throw new InvalidOperationException("Tagged item cannot contain zero value comments");
totalComments += taggedItem.comments;
bool found = false;
foreach (var tag in taggedItem.Tags)
{
if (tag.Value == ".NET")
{
found = true;
break;
}
}
if (!found) // Check the required tag was found
throw new InvalidOperationException(
string.Format("Tagged item does not contain requisite tag - {0}", requiredTag));
}