Richlewis
Richlewis

Reputation: 15374

Creating a Hash from retrieved XML

I have read a few posts that advice you can create a Hash from XML using Rails built in method

from_xml

so for example i could do

Hash.from_xml(object)

In my case I am retrieving XML from an api and using Nokogiri to parse it, like so

url = "https://www.google.com/m8/feeds/contacts/default/full?client_id=#{client_id}&access_token=#{current_user.token}&max-results=#{max_results}";
doc = Nokogiri::XML(open(url))

Now if i try

Hash.from_xml(doc)

I receive a REXML parse error. Is this because i need to create the Hash from unparsed XML?

I am looking to gain a better understanding of this, documents i have read seem to be very high level, if any could offer just a basic explanation or point to a resource that does, I can read it and look to gain a better understanding

Upvotes: 1

Views: 693

Answers (1)

Chowlett
Chowlett

Reputation: 46657

It is expecting a string.

Although this docs page doesn't say so in its method description, it's clear from the example in the notes that the input should be an XML string.

You should be able to do:

Hash.from_xml(open(url).read)

Edit: It appears that, under Rails, Nokogiri has a to_hash method. So you can also do:

doc = Nokogiri::XML(open(url))
xml_hash = doc.to_hash

Upvotes: 2

Related Questions