# New to Ruby and XML

**URL:** <https://www.ruby-forum.com/t/new-to-ruby-and-xml/59885>\
**Category:** Ruby\
**Created:** [May 8, 2006, 8:30am UTC](https://www.ruby-forum.com/t/new-to-ruby-and-xml/59885 "2006-05-08T08:30:55Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![siguva](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/c5a1d2/32.png) [@siguva](https://www.ruby-forum.com/u/siguva)\
**Post date:** [May 8, 2006, 8:30am UTC](https://www.ruby-forum.com/t/new-to-ruby-and-xml/59885/1 "2006-05-08T08:30:55Z")

</div>

Hi all,

I have an API call to another database app that returns the XML below:

9 ISA 8  
AAA 1 AAA   
2 AAB   
 4 AAC  
 5 AAD 7  
AAE 12 AAF   
 13 AAG

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.

Any ideas? Thank you for helping a noob!

-Hunter

---

<div class="post-metadata">

**Author:** ![siguva](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/c5a1d2/32.png) [@siguva](https://www.ruby-forum.com/u/siguva)\
**Post date:** [May 8, 2006, 1:56pm UTC](https://www.ruby-forum.com/t/new-to-ruby-and-xml/59885/2 "2006-05-08T13:56:25Z")

</div>

On Mon, 2006-05-08 at 15:31 +0900, Hunter W. wrote:

> 5 AAD 7  
> AAE 12 AAF   
> 13 AAG
> 
> 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.

If you want to parse the XML you could do it with libxml-ruby  
([http://libxml.rubyforge.org/](http://libxml.rubyforge.org/)), e.g.

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,
