This post originated from an RSS feed registered with Java Buzz
by dion.
Original Post: LINQ 101 to Ruby 101 to Groovy 101
Feed Title: techno.blog(Dion)
Feed URL: http://feeds.feedburner.com/dion
Feed Description: blogging about life the universe and everything tech
def d = ["2005-09" : "September 2005", "2005-08" : "August 2005"]
def a = ["greasemonkey", "ajax"]
def rss = new XmlParser().parse("blog.xml")
def xml = new groovy.xml.MarkupBuilder(new PrintWriter(System.out))
rss.channel.item.findAll { item ->
d.keySet().any { day ->
t(item.date) =~ day;
} && a.any { tag ->
t(item.tags) =~ tag;
}
}.sort { x, y -> t(y.date) <=> t(x.date) }.each { i ->
xml.item() {
month(d[d.keySet().find { key -> t(i.date) =~ key }])
date(t(i.date))
title(t(i.title))
tags(t(i.tags))
}
}
def t(node) { return node[0]!=null ? node[0].text() : '' }
There are some uglies in there (especially the "node to text" pain), but I do prefer the native build syntax that we have in Ruby and Groovy, compared to nesting new XElement("item", ....). They could easily add more sugar to make that work on the .NET side of course.
The other interesting differences are that I didn't use XPath in the Groovy version, and the lack of SQL like stuff. Here it is just method chaining. No need for a special orderby, you simply do a sort. Of course, the beauty of LINQ is its polymorphism across XML, SQL, etc etc.