Java Reference
In-Depth Information
“I kept waiting for you to say, 'this is the hard way,'” she said, “and now here's the easy
way, but you never got to the easy way.”
In reply I had to say, “Want to see the easy way? Let's look at the Groovy solution to this
problem.”
def root = new XmlSlurper().parse('books.xml')
println root.book[1].title
How's that for easy? I instantiated an XmlSlurper , called its parse method on the
XML file, and just walked the tree to the value I want.
If I ever need to parse or generate XML I always add a Groovy module to do it.
Let's look at another, somewhat more practical, example. Remember the Google geocoder
used in chapter 3 ? When the geocoder went to version 3, Google removed the requirement
to register for a key (good) but also removed the CSV output type (unfortunate). Now the
only available output types are either JSON or XML. Google also changed the URL for
accessing the web service (pretty typical when versioning a web service, actually), embed-
ding the two available output types into the new URLs. In chapter 9 on RESTful web ser-
vices I'll have a lot more to say about the choice of output types (formally known as con-
tent negotiation ), but here the type is embedded in the URL.
From a Java point of view, working with JSON output is a bit of a complication because
it requires an external library to parse the JSON data. That's not too much of a burden be-
cause there are several good JSON libraries available, but you still have to pick one and
learn to use it. We've already talked about how involved it is to work with XML data in
Java, so that's not a great alternative either.
Groovy, however, eats XML for lunch. Let's see just how easy it is for Groovy to access
the new geocoder and extract the returned latitude and longitude data.
First, here's a sample of the XML output returned from the web service for the input ad-
dress of Google's home office:
Search WWH ::




Custom Search