簡體   English   中英

Ruby:nil:NilClass的未定義方法“ <<”

[英]Ruby: undefined method `<<' for nil:NilClass

我有一個CSV文件,我想將所有哈希值保存在上面。 我正在使用nokogiri sax解析xml文檔,然后將其保存為CSV。

它解析並保存第一個xml文件,但是當開始解析第二個xml文件時,它停止了,我得到的錯誤是:

錯誤: NoMethodError: undefined method nil:NilClass`的NoMethodError: undefined method <<'

nil錯誤出現在@infodata [:titles] << @content中

薩克斯解析器:

require 'rubygems'
require 'nokogiri'
require 'csv'

class MyDocument < Nokogiri::XML::SAX::Document

  HEADERS = [ :titles, :identifier, :typeOfLevel, :typeOfResponsibleBody, 
              :type, :exact, :degree, :academic, :code, :text ]

  def initialize
     @infodata = {}
     @infodata[:titles] = Array.new([])
  end

  def start_element(name, attrs)
    @attrs = attrs
    @content = ''
  end
  def end_element(name)
    if name == 'title'
      Hash[@attrs]["xml:lang"]
      @infodata[:titles] << @content
      @content = nil
    end
    if name == 'identifier'
       @infodata[:identifier] = @content
       @content = nil
    end
    if name == 'typeOfLevel'
       @infodata[:typeOfLevel] = @content
       @content = nil
    end
    if name == 'typeOfResponsibleBody'
       @infodata[:typeOfResponsibleBody] = @content
       @content = nil
    end
    if name == 'type'
       @infodata[:type] = @content
       @content = nil
    end
    if name == 'exact'     
       @infodata[:exact] = @content
       @content = nil
    end
    if name == 'degree'
       @infodata[:degree] = @content
       @content = nil
    end
    if name == 'academic'
       @infodata[:academic] = @content
       @content = nil
    end
    if name == 'code'
       Hash[@attrs]['source="vhs"']
       @infodata[:code] = @content 
       @content = nil
    end
    if name == 'ct:text'
       @infodata[:beskrivning] = @content
       @content = nil
    end 
  end
  def characters(string)
    @content << string if @content
  end
  def cdata_block(string)
    characters(string)
  end
  def end_document
    File.open("infodata.csv", "ab") do |f|
      csv = CSV.generate_line(HEADERS.map {|h| @infodata[h] })
      csv << "\n"
      f.write(csv)
    end
  end
end

為文件夾中存儲的每個文件創建一個新對象(47.000xml文件):

parser = Nokogiri::XML::SAX::Parser.new(MyDocument.new)
counter = 0

Dir.glob('/Users/macbookpro/Desktop/sax/info_xml/*.xml') do |item|
  parser.parse(File.open(item, 'rb'))
  counter += 1
  puts "Writing file nr: #{counter}"
end

3個用於嘗試代碼的xml文件: https : //gist.github.com/2378898 https://gist.github.com/2378901 https://gist.github.com/2378904

您正在執行此操作:

csv = CSV.generate_line(HEADERS.map {|h| @infodata[h] })
csv << "\n"

如果由於某些原因CSV.generate_line(HEADERS.map {|h| @infodata[h] })返回nil ,則您將嘗試對未定義的nil對象使用<<方法。

您可能需要添加一些條件,以避免在cv中添加“ \\ n”(如果為零)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM