acacia
acacia

Reputation: 1387

Read XML responses in to Rails

I have a URL in my controller that when called return an XML response. Let say, the response looks like this;

<?xml version="1.0" encoding="UTF-8"?>
<AutoCreate>
<Response>
    <Status>YES</Status>
    <name>JOSEPH</name>
    <location>HOME</location>
</Response>
</AutoCreate>

How can i read these values status, name and location into variables in my controller and use them.

Thank you in advance.

Upvotes: 1

Views: 1064

Answers (4)

Ndeto
Ndeto

Reputation: 315

So heres an update for Rails 5,

If you are receiving an XML response the header will be 'application/xml' You access the data using

#read the response and create a Hash from the XML
response = Hash.from_xml(request.body.read)

#read value from the Hash
status = response["AutoCreate"]["Response"]["Status"]

Upvotes: 1

midglide
midglide

Reputation: 1

You can use https://github.com/alsemyonov/xommelier

feed = Xommelier::Atom::Feed.parse(open('spec/fixtures/feed.atom.xml'))
puts feed.id, feed.title, feed.updated

feed.entries do |entry|
  puts feed.id, feed.title, feed.published, feed.updated
  puts feed.content || feed.summary
end

Upvotes: 0

acacia
acacia

Reputation: 1387

If the value of respose.body is;

<?xml version="1.0" encoding="UTF-8"?>
<AutoCreate>
<Response>
    <Status>YES </Status>
    <name> JOSEPH </name>
    <location> HOME </location>
</Response>
</AutoCreate>

Then i think this should be fine.

require ‘active_support’ 
result = Hash.from_xml(response.body)

then;

result.status  == "YES"

Would this work?

Upvotes: 0

user2935448
user2935448

Reputation: 51

can you try this,

response_json = Hash.from_xml(response).to_json

Upvotes: 1

Related Questions