From: Robert Klemme Date: 2008-09-16T05:12:47+09:00 Subject: Re: ruby / rexml / xpath bug? On 15.09.2008 21:38, altinsel wrote: > I'm doing something I would think is very straight-forward but am > getting the strangest result. I'm wondering if anyone could help to > let me know if this is a bug or if I'm doing something I can't see.. > > I copied a Google Maps script from Google Maps with Rails and Ajax > straight from code. It requests a geocoding from Google and parses > the XML using rexml. When it gets to the address with 2 results, the > "each" iterator is looping through, but on the second element is > giving me info from the first. below is the script exactly. > > require 'open-uri' > require 'rexml/document' > > # Retrieve geocode information for all records in the Stores table > task :google_geocode => :environment do > api_key=GOOGLE_MAPS_KEY > > (Store.find :all).each do |store| > > puts "\nStore: #{store.name}" > puts "Source Address: #{store.full_address}" > > xml=open("http://maps.google.com/maps/geo? > q=#{CGI.escape(store.full_address)}&output=xml&key=#{api_key}").read > doc=REXML::Document.new(xml) > > puts "Status: "+doc.elements['//kml/Response/Status/code'].text > > if doc.elements['//kml/Response/Status/code'].text != '200' > puts "Unable to parse Google response for #{store.name}" > else > doc.root.each_element('//Response') do |response| > response.each_element('//Placemark') do |place| > #there are 2 "Placemarks" in one particular "Response" > lng,lat=place.elements['Point/ > coordinates'].text.split(',') This seems weird: you search for potential multiple elements but use method "text" on the result. Not sure what this is going to yield but I'd rather iterate. > puts " Result Address: " << place.elements['// > address'].text see above > # the address, lat and lng come from the 1st element twice > puts " ID: " << place.attributes['id'] > # .. but the 'id' is correct. > puts " Latitude: #{lat}" > puts " Longitude: #{lng}" > end # end each place > end # end each response > end # end if result == 200 > end # end each store > end # end rake task > > ##### > > What I don't understand, is that the XML for each "place" is correct, > but the place.elements['//address'] keeps finding the previous > iterations information. How can this be? Hm, weird. Are you sure the XML is as expected? Btw, you can combine searching for //Response and //Placemark in one since you do not do anything with "Response". Kind regards robert