How do I convert an XML body to a hash in Ruby?
I have an XML body which I\'d like to parse into a hash
If you don't mind using a gem, crack does a pretty good job at this.
Crack does the XML to hash processing, then you can loop over the resulting hash to normalize the datetimes.
edit Using REXML, you could try the following (should be close to working, but I do not have access to a terminal so it may need some tweaking):
require 'rexml/document'
arr = []
doc = REXML::XPath.first(REXML::Document.new(xml), "//soap:Body/TimesInMyDAY").text
REXML::XPath.each(doc, "//TIME_DATA") do |el|
start = REXML::XPath.first(el, "//StartTime").text
end = REXML::XPath.first(el, "//EndTime").text
arr.push({:start_time => Time.parse(start).in_time_zone(current_user.time_zone), :end_time => Time.parse(end).in_time_zone(current_user.time_zone)})
end
hash = { :times_in_my_day => { :time_data => arr } }
Of course, this assumes the structure is ALWAYS the same, and that the example you posted was not contrived for simplicity sake (as examples often are).