blog rss feed

Read and Write XML with Groovy - includes ATOM example

Keywords:

Last editor: Dave Cherry, last modified: Aug 3, 2008

Building XML with Groovy

Groovy supports the concept of builders, which provide an abstraction between the required output content and the representation of it. Groovy supports this by providing a tree like structure in groovy code that represents the required HTML or XML:

import groovy.xml.MarkupBuilder

// create a builder to generate xml like content from a
// builder structure, in this case we choose
// StringWriter as the output, but it could be any writer.
def writer = new StringWriter();
def builder = new MarkupBuilder(writer);

builder.html {
head {
title
"Hello world"
}
body {
h1
"My Hello world page"
p "This is the content"
}
}

println(writer);

So what have we done?

We generated some HTML, in this case we just printed it to the console, but we could have sent this back to a web browser for example, or saved it to disk. The XML structure that we generated from above looked as follows:

<html>
<head>
<title>Hello world</title>
</head>
<body>
<h1>My Hello world page</h1>
<p>This is the content</p>
</body>
</
html>

As can be seen, its very straight forward to write XML formatted data with Groovy. To me this was a major feature when I started looking at the language. On the next page I look at a more complex example, of writing an ATOM syndication document using the builder. This requires namespace support and interaction with closures.

Please leave a comment



Search

Blog calendar

blog: previous month September 2010 blog: next month
su mo tu we th fr sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30