ActiveResource应该忽略root xml元素

时间:2014-06-13 02:35:06

标签: ruby-on-rails rest openstreetmap activeresource

我正在尝试像这样的

连接到REST服务
class Node < ActiveResource::Base
  self.site = "http://www.openstreetmap.org/api/0.6/"
  self.element_name = "node"  
  self.collection_name = "node"
  self.format = ActiveResource::Formats::XmlFormat 
end

但是返回的对象不正确。显然它会读取包含根元素(example of xml here)的整个响应。如何告诉ActiveResource忽略根元素?

返回的对象是

#<Node:0x97952a8 @attributes={"version"=>"0.6", "generator"=>"OpenStreetMap server", "copyright"=>"OpenStreetMap and contributors", "attribution"=>"http://www.openstreetmap.org/copyright", "license"=>"http://opendatacommons.org/licenses/odbl/1-0/", "node"=>#<Node:0x9794740 @attributes={"id"=>"367861148", "changeset"=>"872060", "timestamp"=>"2009-03-31T12:00:25Z", "version"=>"1", "visible"=>"true", "user"=>"pavel", "uid"=>"1066", "lat"=>"50.0077", "lon"=>"14.717027", "tag"=>[#<Node::Tag:0x9925104 @attributes={"k"=>"amenity", "v"=>"restaurant"}, @prefix_options={}, @persisted=true>, #<Node::Tag:0x99249fc @attributes={"k"=>"created_by", "v"=>"andnav.org"}, @prefix_options={}, @persisted=true>, #<Node::Tag:0x9924150 @attributes={"k"=>"name", "v"=>"restaurace"}, @prefix_options={}, @persisted=true>]}, @prefix_options={}, @persisted=true>}, @prefix_options={}, @persisted=true> 

但它应该只是“节点键”的值。

2 个答案:

答案 0 :(得分:1)

返回的对象不正确。这正是API应该返回的内容。你对节点密钥的值是什么意思?显然你已经知道了节点ID。你想要这个位置吗? tags?你需要为你感兴趣的所有密钥解析returned XML structure,这应该是相当简单的。

答案 1 :(得分:1)

尝试使用自定义格式化程序

class MyXMLFormatter
  include ActiveResource::Formats::XmlFormat

  def decode(xml)
    ActiveResource::Formats::XmlFormat.decode(xml)['node']
  end
end

class Node < ActiveResource::Base
  self.format = MyXMLFormatter.new
end