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
import org.codehaus.groovy.tools.xml.DomToGroovy

def xmlExample = """
<jbi:message tns="http://j2ee.netbeans.org/wsdl/rssWsdl"
type="tns:rssWsdlOperationRequest" version="1.0"
jbi="http://java.sun.com/xml/ns/jbi/wsdl-11-wrapper">
<jbi:part>
<entrylist xmlns="http://xml.netbeans.org/schema/1.0/extensions/rssbc">
<entry>
<title>Entry 1</title>
<link>http://localhost:8000/rss/feed/entry1<link>
<description>First Entry</description>
<publishdate>Dec 7, 1976</publishdate>
</entry>
<entry>
<title>Entry 2</title>
<link>http://localhost:8000/rss/feed/entry2<link>
<description>Second Entry</description>
<publishdate>Dec. 7, 1976</publishdate>
</entry>
</entrylist>
</jbi:part>
</jbi:message>
"""

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))

converter.print(document)
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:jbi:'http://java.sun.com/xml/ns/jbi/wsdl-11-wrapper',
xmlns:tns:'http://j2ee.netbeans.org/wsdl/rssWsdl') {
jbi:part) {
EntryList(xmlns:'http://xml.netbeans.org/schema/1.0/extensions/rssbc') {
Entry) {
title('Entry 1')
link('http://localhost:8000/rss/feed/entry1')
description('First Entry')
publishDate('Dec 7, 1976')
}
Entry) {
title('Entry 2')
link('http://localhost:8000/rss/feed/entry2')
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.