I'd like to loop through each of these records and create a hash. The
first value of each record being the key and the second being the value
in the hash.
require 'xml/libxml'
d = XML::Parser.string(xml).parse
h = d.find('/records/record').inject({}) do |h,n|
data = n.find('f').to_a
h.merge!({data.first.content => data.last.content})
end
However, you don't really need to iterate the records, assuming your XML
is structured just as above:
require 'xml/libxml'
d = XML::Parser.string(xml).parse
h = Hash[*d.find('/records/record/f').map { |n| n.content}]
This translates pretty easily to REXML if you don't have libxml-ruby
installed:
require 'rexml/document'
require 'rexml/xpath'
d = REXML::Document.new(xml)
h = Hash[*REXML::XPath.match(d.root, '/records/record/f').map { |n|
n.get_text }]
(Maybe that can be done better, I don't know REXML too well I'm
afraid).
Hope that helps,
···
On Mon, 2006-05-08 at 15:31 +0900, Hunter Walker wrote:
Hi all,
I have an API call to another database app that returns the XML below:
I'd like to loop through each of these records and create a hash. The
first value of each record being the key and the second being the value
in the hash.