2013-02-02 70 views
0

背景XML響應紅寶石散列

我有一個來自設備REST API的XML響應我需要挑出一個特定的鍵/值對。目前我使用HTTParty來檢索XML並挑選文本。我認爲我正在努力做到這一點,並且必須有一個更簡單的方法。

質詢

有沒有做到這一點,使其更容易理解,讓更多的可重複使用的更簡單的方法?

XML看起來像這樣。我試圖挑出格式化的「關」鍵/值對。我目前使用

<?xml version="1.0" encoding="UTF-8"?><properties><property id="ST" value="0" formatted="Off" uom="on/off"/></properties> 

代碼:

require 'httparty' 

    class Rest 
    include HTTParty 
    format :xml 
     end 

    listen_for (/status (.*)/i) do |input| 
    command_status input.downcase.strip 
    request_completed 
    end 

    def command_status(input) 
    inputst = @inputSt[input] 
    unless inputst.nil? 
     status = status_input(inputst) 
     say "#{input} is #{status}" 
    else 
     say "I'm sorry, but I am not programmed to check #{input} status." 
    end 
end  

def status_input(input) 
    # Battery operated devices do not continuously reports status, thus will be blank until first change after an ISY reboot or power cycle. 
    resp = Rest.get(@isyIp + input, @isyAuth).inspect 
    resp = resp.gsub(/^.*tted"=>"/, "") 
    status = resp.gsub(/", "uom.*$/, "") 
    return status.downcase.strip 
    end 
+1

爲什麼不使用'parsed_response'?或者至少,做真正的XML解析,而不是用正則表達式僞造它? –

+0

這就是我希望有人會提供一個例子如何做。 – Elvis

回答

0

我想出如何使用parsed_response和理解所產生的HASH深度解析XML成HASH。謝謝你的提示,Dave!

def status_input(input) 
    # Battery operated devices do not continuously reports status, thus will be blank until first change after an ISY reboot or power cycle. 
    resp = Hash[Rest.get(@isyIp + input, @isyAuth).parsed_response] 
    status = resp["properties"]["property"]["formatted"] 
    return status.downcase.strip 
    end 

感謝您的幫助!