DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Use XmlSimple To Convert XML To A Hash

03.26.2010
| 8094 views |
  • submit to reddit
        Rather than use my own hand-crafted XML-to-Hash code I decided to give XmlSimple a try.  In this example I use the dynarex file scotruby2010-all.xml as the source xml to be converted to a hash.

<pre>
gem1.9.1 install xml-simple
Successfully installed xml-simple-1.0.12
1 gem installed
Installing ri documentation for xml-simple-1.0.12...
Updating class cache with 1871 classes...
Installing RDoc documentation for xml-simple-1.0.12...
</pre>
require 'xmlsimple'
#=> true
user = XmlSimple.xml_in('scotruby2010-all.xml')
<pre>
#=> {"summary"=>[{"title"=>["#scotruby speakers 2010"], "source"=>["http://twitter.com/drobertson/scotruby2010"], "recordx_type"=>["dynarex"]}], "records"=>[{"item"=>[{"name"=>["Jim Weirich"], "twitter_name"=>["jimweirich"], "twitter_id"=>["9070452"], "location"=>["iPhone: 39.229713,-84.521942"], "followers_count"=>["2510"], "friends_count"=>["368"], "bio"=>["Ruby Enthusiast"]}, {"name"=>["Joseph Wilk"], "twitter_name"=>["josephwilk"], "twitter_id"=>["14321259"], "location"=>["London"], "followers_count"=>["316"], "friends_count"=>["104"], "bio"=>["Monkey amongst men"]}, {"name"=>["Brian Marick"], "twitter_name"=>["marick"], "twitter_id"=>["8864512"], "location"=>["Champaign, IL, USA"], "followers_count"=>["2228"], "friends_count"=>["346"], "bio"=>["Agile consultant, dabbler in many things. Dilettante by trade. "]}, {"name"=>["Joe O'Brien"], "twitter_name"=>["objo"], "twitter_id"=>["1315011"], "location"=>["Columbus, Ohio"], "followers_count"=>["1619"], "friends_count"=>["471"], "bio"=>["Ruby evangelist, Geek, Father, Friend"]}, {"name"=>["Carl Lerche"], "twitter_name"=>["carllerche"],
...
</pre>
item = user['records'][0]['item']
item[0]['name']
#=> ["Jim Weirich"]

item[0]['twitter_name']
#=> ["jimweirich"]

item[1]['name']
#=> ["Joseph Wilk"]

item[1]['twitter_name']
#=> ["josephwilk"]

Resources:
 - <a href="http://xml-simple.rubyforge.org/">XmlSimple - XML made easy</a> [rubyforge.org]