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"=&gt;"",
"xml_for_demo"=&gt;"inner text",
"no"=&gt;"52660xxxxxxxxxxx79",
"holder"=&gt;"Franz Fluchsfinger",
"signature"=&gt;"a5f4e2shortened4b1e523ca873837c8f1c9ea66ee1924d",
"type"=&gt;"master",
"valid_until"=&gt;"09/10",
"kpn"=&gt;"",
"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 *