Getting Groovy, Part III
Written By: James Williams
- 22 Aug 2006 -
Description: This tutorial is the third part of a series introducing the major features of Groovy, a dynamic scripting language for the Java Virtual Machine. We will be covering annotations, XML files, and file input/output.
XML Files
Consuming and creating XML documents is deceptively simple in Groovy (even more so that JDOM). Groovy uses what it calls builders to read and create structured documents and graphical user interfaces. The root element in this case is the albums element which takes a single attribute "owner" and its respective value. Everything between its curly braces are children of the root element. The element definitions resemble function calls and, as a result, are easy to read.
def builder = new groovy.xml.MarkupBuilder() builder.albums(owner:'James') { album(name:'Flowers') { photo(name:'rose.jpg') } album(name:'people') { photo(name:'john.jpg', desc:'picture of John') } }
The above builder generates the following text.
<albums owner='James'> <album name='flowers'> <photo name='rose.jpg' /> </album> <album name='people'> <photo name='john.jpg' desc='picture of John' /> </album> </albums>
Reading files is a little more complicated. Given the following file:
<inventory> <section name="fiction"> <book author="Jean-Paul Satre" title="La Peste" /> <book author="Jean-Paul Satre" title="The Stranger" /> </section> <section name="non-fiction"> <book author="Bill Clinton" title="My Life" >Pages</book> <book author="Hilary Clinton" title="It Takes A Village..." /> </section> </inventory>
To list all the books and their content from each section using Groovy, we use the following script.
inventoryXML = new XmlParser().parse("inventory.xml") for (section in inventoryXML) { println "Section: " + section['@name'] for(book in section) { println book['@title'] + " by " + book['@author'] if (book.text() != "") println "Content: " + book.text() } }
Attributes are retrieved with the an @ and the attribute name encased in single quotes and brackets. Content, specifically non-element data, can be retrieved using the text() function. For simplicity, I used the names of the elements but it's not required. section in inventory is really telling groovy to retrieve the direct children of the root element.