2013-10-30 44 views
1

我的控制器中有一個URL,當它被調用時返回一個XML響應。比方說,答案看起來像這樣;將XML響應讀入Rails

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

我如何可以讀取這些值statusnamelocation到變量在我的控制器,並使用它們。

預先感謝您。

+3

看看[this](http://stackoverflow.com/questions/11139709/converting-from-xml-name-values-into-simple-hash) – Christian

回答

0

如果respose.body的值是;

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

然後我認爲這應該沒問題。

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

然後;

result.status == "YES" 

這項工作?

1

你可以試試這個,

response_json = Hash.from_xml(response).to_json 
0

您可以使用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 
0

因此,繼承人爲Rails 5的更新,

如果您收到一個XML響應頭會'application/xml' 您使用數據訪問

#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"]