The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
What's New in Edge Rails: Create a Hash from XML

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
rwdaigle

Posts: 312
Nickname: rwdaigle
Registered: Feb, 2003

Ryan is a passionate ruby developer with a strong Java background.
What's New in Edge Rails: Create a Hash from XML Posted: Jun 27, 2006 7:47 AM
Reply to this message Reply

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.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by rwdaigle
Latest Posts From Ryan's Scraps

Advertisement

Hash has 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).

For instance, this:

Hash.create_from_xml <<EOX
<user>
  <id type="integer">1</id>
  <user-name>ryan</user-name>
</user> 
EOX

gets you this hash:

{ :user => { :id => 1, :user_name => "ryan" } }

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:

hash = Hash.create_from_xml <<EOX
<users>
  <user>
    <id type="integer">1</id>
    <user-name>ryan</user-name>
  </user> 
  <user>
    <id type="integer">2</id>
    <user-name>doug</user-name>
  </user>
</users>
EOX

hash[:users] #=> { :user => { :id => 1, :user_name => "ryan" },
                    :user => { :id => 2, :user_name => "doug" } }

hash[:users][:user].last #=> { :id => 2, :user_name => "doug" }

All in all just a really easy way to process XML.

tags: rails, rubyonrails, xml

Read: What's New in Edge Rails: Create a Hash from XML

Topic: Globalize at Railsconf, Streamlined unveiled Previous Topic   Next Topic Topic: RailsConf is for opinionated geeks

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use