2013-02-02 2 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> 

코드 : 나는 parsed_response를 사용하고 결과 HASH 깊이를 이해 해시로 XML을 구문 분석하는 방법을 알아 냈

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

. 팁 (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 

감사합니다.

관련 문제