0

背景

我有来自设备 REST API 的 XML 响应,我需要选择一个特定的键/值对。目前我正在使用 HTTParty get 来检索 XML 并挑选出文本。我认为我正在以艰难的方式做到这一点,并且必须有一个更简单的方法。

问题

有没有更简单的方法来实现这一点,使其更容易理解和更可重用?

XML 看起来像这样。我正在尝试选择 formatted="Off" 键/值对。

<?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
4

1 回答 1

0

我想出了如何使用parsed_response并理解生成的 HASH 深度将 XML 解析为 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

谢谢你的帮助!

于 2013-02-03T02:29:51.790 回答