Tree like structures in Groovy

As I've mentioned before, Groovy is a Java scripting language being developed in part by the prolific James Strachan. I was home sick on Friday and spent some time looking at it.

One aspect of the language I find particularly intriguing is its built in support for tree syntax. Here's a little HTML generation snippet I wrote in Groovy that uses the tree syntax

h = new MarkupBuilder()
h.html() {
head() {
title("Page Title")
}
body(){

h1("Hello World")
div(id:'Foo') {
div("Content")
}
}
}

This code would generate some simple HTML like:

<html>
<head><title>Page Title</title></head>
<body>
<h1>Hello World</h1>
<div id='Foo'><div>Content</div></div></body>
</html>

The cool thing is that the content of the tree syntax can be more Groovy code. Instead of just outputting one h1 with the message Hello World I could write something like this:

h = new MarkupBuilder()
h.html() {
head() {
title("Page Title")
}
body(){

for (x in ["World", "Pete", "Bob"]) {
h1("Hello "+x)
}
div(id:'Foo') {
div("Content")
}
}
}

The language also has an XPath like syntax called GPath that allows you to select subsets of these tree like structures. I haven't played around with this yet but it looks very powerful. This is an example from the doc.

>>> println( listOfPeople.findAll { it.location == 'UK'}.name );
["James"]

The language is still evolving so it has some rough edges. Also the doc is pretty sparten so be prepared to dig through the test code to find some examples.

Comments

Popular posts from this blog

Shark Crackers

Running roughshod or ripshod

Axis, Axes, Axii?