Saturday, October 6, 2007

Converting Dom to Groovy Code

I've been looking into and learning a little Groovy on the side. One of the things I'm most interested in is learning how to use the MarkupBuilder provided by Groovy. Essentially this, in my opinion, is a much better way to parse and construct XML. As a developer I use XML almost daily. First I'm looking at integrating this into my unit tests. Today I stumbled on the DomToGroovy class and found this pretty cool. I was trying to figure out how to construct XML using Groovy. I knew what the XML looked liked, so using the DomToGroovy class I could get a good idea what the Groovy code would look like that I needed to write. Below is a sample of how to do this, and I recommend the GroovyConsole to test with.

import javax.xml.parsers.DocumentBuilderFactory

def xmlExample = """
<jbi:message tns=""
type="tns:rssWsdlOperationRequest" version="1.0"
<entrylist xmlns="">
<title>Entry 1</title>
<description>First Entry</description>
<publishdate>Dec 7, 1976</publishdate>
<title>Entry 2</title>
<description>Second Entry</description>
<publishdate>Dec. 7, 1976</publishdate>

def builder = DocumentBuilderFactory.newInstance().newDocumentBuilder()
def inputStream = new ByteArrayInputStream(xmlExample.bytes)
def document = builder.parse(inputStream)
def output = new StringWriter()
def converter = new DomToGroovy(new PrintWriter(output))

println output.toString()

The output essentially shows you what the Groovy code would look like to construct the XML that we provided.

jbi:message(type:'tns:rssWsdlOperationRequest', version:'1.0',
xmlns:tns:'') {
jbi:part) {
EntryList(xmlns:'') {
Entry) {
title('Entry 1')
description('First Entry')
publishDate('Dec 7, 1976')
Entry) {
title('Entry 2')
description('Second Entry')
publishDate('Dec. 7, 1976')

I think this is a pretty slick way to quickly generate a code sample so that you can quickly get started. More to come on Groovy later......

1 comment:

Cynthia said...

You write very well.