Java Reference
In-Depth Information
The result of all this string manipulation is to create a full URL, similar to the one shown
in the previous example, which can be transmitted to the Google geocoder.
Now comes the fun part. The geocoder returns a fairly extensive block of XML (not
shown here, but available online in the Google geocoder documentation at ht-
tps://developers.google.com/maps/documentation/geocoding/#XML ) . Processing the
XML using Java would be quite verbose. Fortunately, XML is nothing to Groovy. The en-
tire process of transmitting the URL to the Google geocoder and parsing the result into a
DOM tree takes one line:
def response = new XmlSlurper().parse(url)
Groovy has two classes for parsing XML. One is called XmlParser , and the other is Xm-
lSlurper . Both convert XML into a DOM tree. The underlying structure and process
are somewhat different, but from a practical point of view the slurper is more efficient and
takes less memory, so that's what I'll use here. Extracting the results I need is a simple mat-
ter ofwalking the tree. Icould paste in a copy ofthe XML output to showyouthe structure,
but it's easy enough to understand if you see the Groovy parsing code:
stadium.latitude = response.result[0].geometry.location.lat.toDouble() [ 6 ]
stadium.longitude = response.result[0].geometry.location.lng.toDouble()
6 Try that in Java. Nothing sells Groovy to Java developers like working with XML.
In other words, the slurper returns the root of the DOM tree, which is assigned to a variable
called response . The root has a child element called result , which has a child called
geometry , which has a child called location , which then has two children, one called
lat and the other called lng . Sometimes the geocoder returns multiple results, so I used
the array index 0 on result to use only the first one. Because everything in XML is a
String and I want to assign the results to double values in Stadium , I finally use the
toDouble method added to String to do the conversion.
Parsing XML
Whether you use an XmlParser or an XmlSlurper , extracting data from XML means
just walking the tree. [ 7 ]
7 Parsing (actually, slurping) JSON is just as easy. The topic source code for chapter 2 includes another example that
accesses and parses JSON data.
 
 
Search WWH ::




Custom Search