解析XML HTTParty响应

时间:2016-12-24 06:03:19

标签: ruby-on-rails ruby xml xml-parsing httparty

我使用HTTParty从api获取数据。我设法恢复了XML响应,看起来HTTParty已经将xml响应变成了Ruby。

如何浏览哈希值并获取所需的数据?例如,假设我想要“名称”,即“第29个AVENUE STN / ARBUTUS”。

API密钥工作正常,因为我收到了回复。

我不太确定如何浏览并获取我想要的数据,并将其放入我的视图中。

index.html.erb:

public function handle(Request $request, $url)
{
    // logic to search and render your vanity page for $url

    // if no vanity page was found:
    throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
}

HTTparty回复:

<% @courses.each do |course| %>
<%= course %>

<% end %>

获得回复的模型

["Route", {
"RouteNo" => "016", "Name" => "29TH AVENUE STN/ARBUTUS ", "OperatingCompany" => "CMBC", "Patterns" => {
    "Pattern" => [{
        "PatternNo" => "E5TP", "Destination" => "29TH AVE STN", "RouteMap" => {
            "Href" => "http://nb.translink.ca/geodata/trip/016-E5TP.kmz"
        }, "Direction" => "EAST"
    }, {
        "PatternNo" => "EB1", "Destination" => "29TH AVE STN", "RouteMap" => {
            "Href" => "http://nb.translink.ca/geodata/trip/016-EB1.kmz"
        }, "Direction" => "EAST"
    }, {
        "PatternNo" => "EB5", "Destination" => "29TH AVE STN", "RouteMap" => {
            "Href" => "http://nb.translink.ca/geodata/trip/016-EB5.kmz"
        }, "Direction" => "EAST"
    }]
}
}]

模型的控制器

class Checker

include HTTParty

base_uri 'http://api.translink.ca/rttiapi/v1/routes'
default_params apikey: "[my proper api key]"
format :xml

def self.for term
  get("", query: {stopNo: term})["Routes"]["Route"]["RouteNo"]
  end
end

1 个答案:

答案 0 :(得分:0)

假设您有回复:

resp = ["Route", {
"RouteNo" => "016", "Name" => "29TH AVENUE STN/ARBUTUS ", "OperatingCompany" => "CMBC", "Patterns" => {
    "Pattern" => [{
        "PatternNo" => "E5TP", "Destination" => "29TH AVE STN", "RouteMap" => {
            "Href" => "http://nb.translink.ca/geodata/trip/016-E5TP.kmz"
        }, "Direction" => "EAST"
    }, {
        "PatternNo" => "EB1", "Destination" => "29TH AVE STN", "RouteMap" => {
            "Href" => "http://nb.translink.ca/geodata/trip/016-EB1.kmz"
        }, "Direction" => "EAST"
    }, {
        "PatternNo" => "EB5", "Destination" => "29TH AVE STN", "RouteMap" => {
            "Href" => "http://nb.translink.ca/geodata/trip/016-EB5.kmz"
        }, "Direction" => "EAST"
    }]
}
}]

又是两个元素的数组,首先是&#39; Route&#39;并且最后一个是具有所有属性的哈希,以简单地使用名称:

resp.last['Name']