2013-06-13 66 views
11

我使用一些服務,返回XML在Rails的哈希:轉換XML字符串

response = HTTParty.post(service_url) 
response.parsed_response 
=> "\n\t<Result>\n<success>\ntrue\n</success>\n</Result>" 

我需要這個字符串散列轉換。類似這樣的:

response.parsed_response.to_hash 
=> {:result => { :success => true } } 

哪種方式可以做到這一點?

+1

http://www.railstips.org/blog/archives/2008/08/11/parsing-xml-with-ruby/ –

回答

27

內置from_xml Rails Hash方法將正是你想要的。爲了讓您的response.parsed_response正確映射到一個哈希,你需要gsub()出新行:

hash = Hash.from_xml(response.parsed_response.gsub("\n", "")) 
hash #=> {"Result"=>{"success"=>"true"}} 

在解析Rails中的哈希的情況下,String類型的對象not substantively different比那些Symbol一般的編程觀點。但是,您可以應用Rails的symbolize_keys方法來輸出:

symbolized_hash = hash.symbolize_keys 
#=> {:Result=>{"success"=>"true"}} 

正如你所看到的,symbolize_keys不會對任何嵌套哈希操作,但你可以通過內部哈希潛在迭代和應用symbolize_keys

拼圖的最後一部分是將字符串"true"轉換爲布爾值true。據我所知,有沒有辦法做到這一點在地方的哈希值,但如果你遍歷/操作它,你可能實現像一個suggested in this post的解決方案:

def to_boolean(str) 
    return true if str == "true" 
    return false if str == "false" 
    return nil 
end 

基本上,當你到達內鍵值對,您可以將to_boolean()應用於當前設置爲"true"的值。在你的例子中,返回值是布爾值true

+0

請看看我的帖子,謝謝 –

2

您可以在下面試試這個: -

require 'active_support/core_ext/hash/conversions'
Hash.from_xml "\n\t<Result>\n<success>\ntrue\n</success>\n</Result>".gsub("\n", "").downcase

輸出: - 我得到了什麼

{"result"=>{"success"=>"true"}}

感謝

+0

感謝包括要求紅寶石外軌使用! – andreofthecape

2

使用寶石Nokogir

doc = Nokogiri::XML(xml_string) 

data = doc.xpath("//Result").map do |result| 
    [ 
    result.at("success").content 
    ] 
end 

這些tutorials可以幫助你。

+0

希望它不會給出確切的散列,因爲我得到了#]>]>]>' –

+0

更新了我的答案。 Tty這個。 – rony36

10

使用nokogiri來解析對ruby hash的XML響應。這很快。

require 'active_support/core_ext/hash' #from_xml 
require 'nokogiri' 

doc = Nokogiri::XML(response_body) 
Hash.from_xml(doc.to_s)