This post originated from an RSS feed registered with Ruby Buzz
by rwdaigle.
Original Post: What's New in Edge Rails: Create a Hash from XML
Feed Title: Ryan's Scraps
Feed URL: http://feeds.feedburner.com/RyansScraps
Feed Description: Ryan Daigle's various technically inclined rants along w/ the "What's new in Edge Rails" series.
Hashhas been extended to provide the ability to create a new hash from an xml string. While this is now used internally by Rails to handle XML requests, it’s also available for use as you see fit.
The basic premise is that XML is mostly a nested set of key => value pairs which is pretty much what a hash is. Population and creation of a hash from an XML structure makes perfect sense and can simplify your use of XML.
What happens when you call Hash.create_from_xml(xml) is that each xml element gets set as a key in the hash and the value of that element is stored as the value in the hash (with typecasting).
Notice how the integer value of the id was actually cast as an integer. Also note how element names such as user-name get modified into the Ruby form user_name.
Collections of more than one item are handled pretty intuitively as well: