JavaDude's Groovy Snippets and Tutorials

December 23, 2009

Create XML file with MarkupBuilder

Filed under: Groovy Snippets — devdude @ 8:45 am
Tags:

The most simple way to create XML content in the standard output or file.

def fw = new FileWriter("/somepath/persons.xml" )
// to write to standard out, remove fw
def xml = new groovy.xml.MarkupBuilder(fw)

xml.content() {

 xml.parameter(x:0)

 xml.person(id:100){
 firstname("John")
 lastname("Long")
 }

 xml.person(id:101){
 firstname("Ken")
 lastname("Smith")
 }
}

Result

<content>
 <parameter x='0' />
 <person id='100'>
 <firstname>John</firstname>
 <lastname>Long</lastname>
 </person>
 <person id='101'>
 <firstname>Ken</firstname>
 <lastname>Smith</lastname>
 </person>
</content>

Please note the difference between MarkupBuilder and StramingMarkupBuilder. More information about XML processing at groovy.codehaus.org
MarkupBuilder is not very flexible, but simple to use for some basic task. If you require comments, XML declarations and more, your rather use the StreamingMarkupBuilder.

Advertisement

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Theme: Rubric. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.