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


master
Franz Fluchsfinger

52660xxxxxxxxxxx79

09/10
Just some data
inner text
a5f4e2shortened4b1e523ca873837c8f1c9ea66ee1924d
eof

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

[/sourcecode]

result:


ruby test.rb
{"company"=>"",
"xml_for_demo"=>"inner text",
"no"=>"52660xxxxxxxxxxx79",
"holder"=>"Franz Fluchsfinger",
"signature"=>"a5f4e2shortened4b1e523ca873837c8f1c9ea66ee1924d",
"type"=>"master",
"valid_until"=>"09/10",
"kpn"=>"",
"data"=>"Just some data"}

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

Tagged with: