I have a hash like,
object = { :type => 'book', :name => 'RoR', :price => 33 }
OR
object = { :type => 'wig', :name => 'Elvis-Style', :price => 40, :color => 'black' }
The problem is that keys in above hash may be different all the time or even increase and decrease depending upon the object type.
What I want to do generate XML for above hashes using Xml::Builder
. The XML tags are decided by the keys
in the hash and text
inside a tag is value corresponding that key.
I can use eval
to do this like below. However, I think there must be a bet开发者_JAVA百科ter way to do it.
object.each do |key, text|
eval("xml.#{key.to_s} do
#{text}
end
")
end
@object.each do |k, v|
xml.tag!(k.to_s, v)
end
Rails supports to_xml
on Hash classes.
hash = { :type => 'book', :name => 'RoR', :price => 33 }
hash.to_xml
# Returns
# <?xml version=\"1.0\" encoding=\"UTF-8\"?>
# <hash>
# <type>book</type>
# <name>RoR</name>
# <price type=\"integer\">33</price>
# </hash>
If you want to skip the types then:
hash.to_xml(:skip_types => true)
If you want to give a different root then:
hash.to_xml(:root => 'options')
This one worked.
@object.each do |k, v|
xml.tag!(k.to_s, v)
end
out << "<#{key}>#{html_escape(value)}</#{key}>"
精彩评论