Over a million developers have joined DZone.

Use XmlSimple To Convert XML To A Hash

DZone's Guide to

Use XmlSimple To Convert XML To A Hash

· ·
Free Resource
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.

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...
require 'xmlsimple' #=> true user = XmlSimple.xml_in('scotruby2010-all.xml')
#=> {"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"],
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: - XmlSimple - XML made easy [rubyforge.org]

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}