Java Reference
In-Depth Information
B.8. XML
I've saved the best for last. XML is where the ease-of-use gap between Groovy and Java is
the largest. Working with XML in Java is a pain at best, while parsing and generating XML
in Groovy is almost trivial. If I ever have to deal with XML in a Java system, I always add
a Groovy module for that purpose. This section is intended to show why.
B.8.1. Parsing and slurping XML
Some time ago, I was teaching a training course on XML and Java. One of the exercises
started by presenting an XML file similar to this one:
<books>
<book isbn= "9781935182443" >
<title>Groovy in Action (2nd edition)</title>
<author>Dierk Koenig</author>
<author>Guillaume Laforge</author>
<author>Paul King</author>
<author>Jon Skeet</author>
<author>Hamlet D'Arcy</author>
</book>
<book isbn= "9781935182948" >
<title>Making Java Groovy</title>
<author>Ken Kousen</author>
</book>
<book isbn= "1933988932" >
<title>Grails in Action</title>
<author>Glen Smith</author>
<author>Peter Ledbrook</author>
</book>
</books>
The goal of the exercise was to parse this file and print out the title of the second book.
Because this file is small, you might as well use a DOM parser to read it. To do that in Java
you need a factory, which then yields the parser, and then you can invoke a parse method
to build the DOM tree. Then, to extract the data, there are three options:
• Walk the tree by getting child elements and iterating over them.
• Use the getElementById method to find the right node, and then get the first
text child and retrieve its value.
• Use the getElementsByTagName method, iterate over the resulting
NodeList to find the right node, and then retrieve the value of the first text child.
Search WWH ::




Custom Search