I have some (not “properly formatted”) XML stored as a string:
xml_data_as_string = "<first_name>John</first_name><last_name>Smith</last_name>"
I’m trying to convert it to a hash so can reference it like so:
@hash[:first_name] # => John
I can accomplish this by doing:
Hash.from_xml("<root>#{xml_data_as_string}</root>")
The from_xml method seems to require that there be a root element for the XML. So I currently have to reference the hash as:
@hash[:root][:first_name] # => John
This is a little inconvenient and I was wondering if there was a simple way to accomplish this. I’ve looked at the API for from_xml and it’s extremely sparse…shows 1 example with no further explanation.
It’s not the end of the world doing it this way, but I would like a cleaner solution.
@hash = Hash.from_xml("<root>#{xml_data_as_string}</root>")[:root]XML data needs to be formatted properly to be parsed, but this way you only have to call
[:root]once. Make sure the data is good or you’ll get an error asking for[:root].