0

I'm making a HTTP request to a public IMDb-style TV episode service. I'm returned data like

<title>The X-Files</title>
<episodes>202</episodes>
<ended>Yes</ended>

And I want to work with that data in my program. Ultimately, I want to use it to form an SQL statement and insert the data into my database.

However, actually turning the data into a hash is harder than I expected. I googled it, and there are a lot of gems that purport to help, like Simple-XML -- but they expect files, and don't seem to behave when I pass them an object containing XML instead.

What's the common and accepted way to do this?

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
GreenTriangle
  • 2,382
  • 2
  • 21
  • 35

2 Answers2

1

I use HTTParty when writing interfaces with services like that. It converts XML responses to a hash automatically. Provide your code and more details if you want a more detailed answer.

Mark Thomas
  • 37,131
  • 11
  • 74
  • 101
1

You can parse normal data as well using SimpleXML gem. Assuming you have installed xml-simple gem already, do

require 'xmlsimple'
xml_str = "<data><title>The X-Files</title><episodes>202</episodes><ended>Yes</ended></data>"
xml_dict = XmlSimple.xml_in(xml_str)

The xml_str variable can be constructed from the http response.

Note that the current data you have <title>The X-Files</title><episodes>202</episodes><ended>Yes</ended> is not valid xml (it looks valid markup but is not, you can check here) and so I had to wrap them up within another parent <data> tag of its own.

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186