xml对ruby哈希的响应

时间:2013-02-02 20:18:02

标签: ruby xml hash

背景

我从设备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 个答案:

答案 0 :(得分:0)

我想出了如何使用parsed_response将XML解析为HASH并理解生成的HASH深度。谢谢你的提示,戴夫!

  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

感谢您的帮助!