2012-06-19 67 views
2

我有以下XML结构:为什么我为#找到一个未定义的方法`xpath'?

<agencies> 
    <city> 
    <name>New York</name> 
    <address>Street A, 101</address> 
    <phone>111-222-333</phone> 
    </city> 
    <city> 
    <name>Chicago</name> 
    <address>Street B, 201</address> 
    <phone>111-222-333</phone> 
    </city> 
</agencies> 

,我试图创建一个Ruby类与它合作。

我创建的类文件:

require 'nokogiri' 

class Agency 

    def initialize(arg) 
    @file = arg.gsub(/-/,'_') 
    @doc = Nokogiri::XML(open("db/agencies/#{@file}.xml")) 
    end 

    def find_offices 
    @doc.xpath('//agencies/city').map do |i| 
     { 'name' => xpath('name') } 
    end 
    #@entries = @doc.xpath('//agencies/city').map do |i| 
    # { 'name' => xpath('name').inner_text, 'address' => xpath('address').inner_text, 'phone' => xpath('phone').inner_text } 
    #end 
    end 
end 

对于我的控制,我有:

class AgenciesController < ApplicationController 

    def index 
    @prefectures = Prefecture.all 
    end 

    def list 
    @prefecture = Agency.new(params[:prefecture_name]) 
    @offices = @prefecture.find_offices 
    end 
end 

list方法返回以下错误:

NoMethodError in AgenciesController#list 

undefined method `xpath' for #<Agency:0x9e7f280> 
Rails.root: /home/kleber/projects/rails_apps/job_board2 

Application Trace | Framework Trace | Full Trace 
app/models/agency.rb:13:in `block in find_offices' 
app/models/agency.rb:12:in `map' 
app/models/agency.rb:12:in `find_offices' 
app/controllers/agencies_controller.rb:9:in `list' 

回答

2

本节看起来很滑稽:

def find_offices 
    @doc.xpath('//agencies/city').map do |i| 
     { 'name' => xpath('name') } 
    end 

您为xpath()查询返回的每个元素创建一个局部变量i,但不使用它。您打电话给xpath('name'),但我没有看到可以调用的类(或全局范围)上的xpath()的定义。

您的意思是写更类似的东西吗? (未经测试):

 { 'name' => i.xpath('name') } 
+0

哦,男人..只是忘了'我'变量! .. 谢谢! –

相关问题