From: Paul Lutus Date: 2006-11-17T08:20:09+09:00 Subject: Re: Ruby newbie & XML - What's the simplest way to get XML data into a hash? darenbell@gmail.com wrote: > Sorry for having such a specific question, but is there a simple way to > take the XML document below and put it into some sort of organized hash > value without first knowing anything about it? > > This is an easy job using something like XML::Simple in Perl, but for > the life of me, I can't figure out an easy way to do this in Ruby. Try this: --------------------------------- #!/usr/bin/ruby -w data = File.read("data.xml") root = {} hash = root stack = [] data.each do |line| line.strip! if line =~ %r{^<\w+>$} tag = line.sub(%r{<(.*?)>},"\\1") stack.push(hash) hash[tag] ||= {} hash = hash[tag] elsif line =~ %r{^$} hash = stack.pop elsif line =~ %r{<(\w+)>.*?} key,value = line.scan(%r{<(\w+)>(.*?)<}).flatten hash[key] = value else puts "Error: undefined case: #{line}" end end def traverse_hash(hash,tab = 0) hash.keys.sort.each do |key| print "#{" " * tab}" if(hash[key].class == Hash) puts "#{key}" traverse_hash(hash[key],tab+1) else puts "#{key} = #{hash[key]}" end end end traverse_hash(root) --------------------------------- Output: environment authentication adminGroup dataType = NULL description = NULL value = NULL bindUserID dataType = NULL description = NULL value = NULL bindUserPassword dataType = NULL description = NULL value = NULL ldapServer dataType = NULL description = NULL value = NULL database databaseHost dataType = NULL description = NULL value = NULL databasePassword dataType = NULL description = NULL value = NULL databasePort dataType = NULL description = NULL value = NULL databaseSchema dataType = NULL description = NULL value = NULL databaseUser dataType = NULL description = NULL value = NULL -- Paul Lutus http://www.arachnoid.com