Hpricot: XML to Hash

On March 20, 2009, in Programmierung, Ruby and Rails, by tov

Well: I nearly lost all my hairs about this. Strange that I couldn’t find something like this in the docs.Situation:

I have some XML code from that I need parts being put into a simple hash (see below).

The following small ruby snippet does exactly this.

Only thing that’s not working is the “inner_xml” part. I personally don’t need it but your mileage may vary and you may want to fix the issue (and give me a note)

[sourcecode language=’ruby’]
require ‘rubygems’
require ‘hpricot’
require ‘pp’

text = < 0

Franz Fluchsfinger


Just some data
inner text

xml =Hpricot.XML(text)
a= xml/”creditcard/*”
a.each {|b|
h[b.name] = b.inner_text if b.is_a? Hpricot::Elem
pp h



ruby test.rb
"xml_for_demo"=&gt;"inner text",
"holder"=&gt;"Franz Fluchsfinger",
"data"=&gt;"Just some data"}

Btw.: I found the solution partly on http://railsforum.com/viewtopic.php?id=22055

Tagged with:  

Leave a Reply

Your email address will not be published. Required fields are marked *